是否有一种相对简单的方法可以为关联数组中的每个键找到最高值?
Array(
0 => Array(
"avgtime" => 19.75,
"bounces" => 3,
"pageviews" => 14,
"visitors" => 4
)
1 => Array(
"avgtime" => 1.125,
"bounces" => 7,
"pageviews" => 9,
"visitors" => 8
)
2 => Array(
"avgtime" => 111,
"bounces" => 18,
"pageviews" => 32,
"visitors" => 20
)
3 => Array(
"avgtime" => 6.9375,
"bounces" => 14,
"pageviews" => 18,
"visitors" => 10
)
4 => Array(
"avgtime" => 191,
"bounces" => 11,
"pageviews" => 57,
"visitors" => 24
)
);
我想创建一个为每个键保存最高值的数组,以便最终得到结果。
Array(
"avgtime" => 191,
"bounces" => 18,
"pageviews" => 57,
"visitors" => 24
);
答案 0 :(得分:3)
迭代数组并存储每个键的最大值
$temp = array();
foreach ($data as $item) {
foreach ($item as $key => $value) {
$temp[$key] = max(
isset($temp[$key]) ? $temp[$key] : $value,
$value);
}
}
答案 1 :(得分:0)
function maxRecursive(array $arr) {
$maxArray = array();
array_walk_recursive($arr, function($val, $key) use(&$maxArray){
if( ( !$maxArray[$key] ) || $maxArray[$key] < $val ){
$maxArray[$key] = $val;
}
});
return $maxArray;
}