
统计重复值和计算金额
想要统计给定数组中的重复值和部门总金额,以下步骤可供参考:
1. 统计重复值
使用 array_count_values() 函数来统计数组中每个部门(org_name 属性)出现的次数。例如:
$counts = array_count_values(array_column($array, 'org_name'));
2. 计算金额
遍历数组以累加每个部门的金额:
$prices = array();
foreach ($array as $item) {
if (isset($prices[$item['org_name']])) {
$prices[$item['org_name']] += $item['price'];
} else {
$prices[$item['org_name']] = $item['price'];
}
}3. 结合结果
将 $counts 和 $prices 数组合并,即可得到包含重复次数和总金额的结果:
$results = array();
foreach ($counts as $org_name => $count) {
$results[$org_name] = array(
'count' => $count,
'price' => $prices[$org_name]
);
}最终结果示例:
Array
(
['部门1'] => Array
(
['count'] => 2
['price'] => 600
)
['部门2'] => Array
(
['count'] => 2
['price'] => 300
)
)以上就是如何统计数组中部门的重复次数及计算部门总金额?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号