看这个数组的例子:这里
基本上,我想在该数组中找到array[]['time']的最大值。如果我循环遍历它,我可以解决它,但我希望有更优雅的解决方案。
看这个数组的例子:这里
基本上,我想在该数组中找到array[]['time']的最大值。如果我循环遍历它,我可以解决它,但我希望有更优雅的解决方案。
如果你想要在数组上进行迭代计算并得到一个单一的值,那么可以考虑使用array_reduce
函数:
$max = array_reduce($array, function($a, $b) {
return $a > $b['time'] ? $a : $b['time'];
} );
或者你可以利用像这样的实用程序函数:
function array_col(array $a, $x)
{
return array_map(function($a) use ($x) { return $a[$x]; }, $a);
}
这将会被使用,例如:
$max = max(array_col($array, 'time'));
它更为通用,可用于其他类似的事情。
array_column
函数来代替你的array_col
函数呢?http://php.net/manual/en/function.array-column.php - Ethan按照[]['time']
从高到低对数组进行排序,并获取第一个值:
function sort_arr($item_1, $item_2)
{
return $item_2['time'] - $item_1['time'];
}
usort($arr, 'sort_arr');
// $arr[0] is the item with the highest time
你可以对数组进行排序,然后分别取第一个或最后一个值。你可以利用usort函数通过提供自定义比较函数来对数组进行排序以反映你的结构。
这里是一个简单的例子:
$foo[1]["time"] = 2323443;
$foo[2]["time"] = 343435;
$foo[3]["time"] = 13455;
$foo[4]["time"] = 9873634;
$foo[5]["time"] = 82736;
$foo[6]["time"] = 9283;
function cmp($a, $b)
{
if ($a["time"] == $b["time"]) {
return 0;
}
return ($a["time"] < $b["time"])
? -1
: 1;
}
usort($foo, "cmp");
$max = $foo[count($foo)-1]["time"];