多维数组查询 PHP

Multidimensional Arrays enquiry PHP

例如我有如下数组:

Array 
(
   [0] => Array
     (
        [a] => 1
        [b] => 0
        [c] => 1
        [d] => 1     
     )
    [1] => Array
    (
        [a] => 2
        [b] => 0
        [c] => 3
        [d] => 3 
    )
    [4] => Array
    (
        [a] => 5
        [b] => 1
        [c] => 3
        [d] => 2 
    )    

)

现在我只想接收具有最大 [d] 值的数组。 所以在这种情况下:

Array (
        [a] => 2
        [b] => 0
        [c] => 3
        [d] => 3
    )  

最简单和最佳的方法是什么? 谢谢!

$res=array();
    foreach ($array as $temp)
    {
        foreach ($temp as $k=>$value)
        {
            if(!isset($res[$k]))
            {
                $res[$k]=$value;
            }
            else
            {
                $res[$k]=max($value,$res[$k]);
            }
        }
    }
    print_r($res);

output Array ( [a] => 5 [b] => 1 [c] => 3 [d] => 3 )

更新答案

$res=array();
    $max=0;
    foreach ($array as $temp)
    {
        if($max<$temp['d'])
        {
             $max=$temp['d'];
            $res=$temp;
        }
    }
    print_r($res);

output Array ( [a] => 2 [b] => 0 [c] => 3 [d] => 3 )

$array = Array 
(
   [0] => Array
     (
        [a] => 1
        [b] => 0
        [c] => 1
        [d] => 1     
     )
    [1] => Array
    (
        [a] => 2
        [b] => 0
        [c] => 3
        [d] => 3 
    )
    [4] => Array
    (
        [a] => 5
        [b] => 1
        [c] => 3
        [d] => 2 
    ));

    uasort ( $array, function ($a, $b) {
            return $a['d'] > $b['d'];
        }
    );

$valueYouAreSearchingFor = $array[0];

我使用 uasort 使用匿名函数对数组进行排序。我必须测试它是否比 ForEach 循环更快,但它肯定更有趣(至少如果你问我:))

如果不想改变原来的数组,就复制一份,对副本进行排序。

PS: Google 是你的朋友...

$subArray1 = array('a' => 1, 'b' => 0, 'c' => 1, 'd' => 1);
$subArray2 = array('a' => 2, 'b' => 0, 'c' => 3, 'd' => 3);
$subArray3 = array('a' => 5, 'b' => 1, 'c' => 3, 'd' => 2);
$data = array($subArray1, $subArray2, $subArray3);

$resultArray = array();
/*
Turn off 'notification' level errors or add 'isset' checks
*/
foreach($data as $subArray)
{
    foreach($subArray as $key => $value)
    {
        $resultArray[$key] = max($resultArray[$key], $value);
    }
}
var_dump($resultArray);