从数组返回整个子数组(包含最大值)

时间:2013-09-05 01:12:25

标签: php

尝试返回键“distance”包含最大值的数组,而不是仅返回值。

即。从:

[0] => Array
    (
        [pid] => 1
        [type] => lj
        [distance] => 211849216
        [maxspeed] => 277598944
        ...
    )
[1] => Array
    (
        [pid] => 1
        [type] => lj
        [distance] => 230286752
        [maxspeed] => 289118816
        ...
    )
[2] => Array
    (
        [pid] => 1
        [type] => lj
        [distance] => 230840928
        [maxspeed] => 298438336
        ...
    )
...

我希望得到[2]

(
    [pid] => 1
    [type] => lj
    [distance] => 230840928
    [maxspeed] => 298438336
    ...
)

我已经能够通过以下方式获得最大值:

function max_dist($a) {
    return $a["distance"];
}
$jump = max(array_map("max_dist", $jumps)));

但与JS /下划线的简单优雅不同:

var jump=_.max(jumps,function(o){
    return +o.distance;
});

它只返回最大距离值。

我必须在PHP中遗漏一些简单的东西!

1 个答案:

答案 0 :(得分:1)

function max_dist($array) {
    $maxIndex = 0;
    $index = 0;
    $maxValue = $array[0]['distance'];
    foreach( $array as $i){
        if($i['distance'] > $maxValue){
            $maxValue = $i['distance'];
            $maxIndex = $index;
        }
    $index++;
    }
    return $array[$maxIndex];
}
$jump = max(array_map("max_dist", $jumps)));