我有一个如下所示的数组:
Array(
[172.17.0.2] => Array
(
[okok] => 1
)
[172.17.0.1] => Array
(
[wp] => 3
[ojopj] => 1
[opjopj] => 1
)
)
我需要能够计算第 2 级内容,然后根据这些总数对顶级数组进行排序。
例如,我的结果数组看起来像这样:
Array(
[172.17.0.2] => 1
[172.17.0.1] => 5
)
理想情况下,我希望按降序排序并仅显示前 5 个结果。
目前我的代码包括以下内容:
foreach ($iplog as $ip => $arr) {
foreach ($arr as $user => $count) {
$count_desc = $count_desc + $count;
}
$output .= $count_desc;
$output .= '</span><hr style="width:100%">';
}
但是,这不会处理任何排序或将结果限制在前 5 名。根据我目前的代码,我只能设想创建更多 for 循环来构建一个新数组,对其进行排序等等上。
是否有更有效的方法来实现我需要的结果?
最佳答案
只需映射到一个函数来对内部数组求和,对前 5 个数组进行排序和切片:
$result = array_map('array_sum', $iplog);
arsort($result);
$top5 = array_slice($result, 0, 5, true);
关于php - 按二级数组计数对数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56794717/