$arr = [
[
'id' => 1,
'name' => '软件开发',
'parent_id' => 0,
'total' => 5
],
[
'id' => 2,
'name' => '系统技术',
'parent_id' => 0,
'total' => 3
],
[
'id' => 3,
'name' => 'PHP',
'parent_id' => 1,
'total' => 6
],
[
'id' => 4,
'name' => 'Javascript',
'parent_id' => 1,
'total' => 10
],
[
'id' => 5,
'name' => 'Windows10',
'parent_id' => 2,
'total' => 12
],
[
'id' => 6,
'name' => 'Windows7',
'parent_id' => 2,
'total' => 68
],
];
/**
* 数组父子级指定字段之和
* @function array_key_sum
* @param $arr 数组
* @param int $level 顶级默认为0
* @return array
* @auth 执笔画卿颜 丶 <365919529@qq.com>
*/
function array_key_sum($arr, $level = 0)
{
if (!empty($arr)) {
$result = [];
foreach ($arr as $key => $value) {
$result[$value['id']] = $value;
}
foreach ($arr as $key => $value) {
// 如果父级为顶级 则不做修改
if ($value['parent_id'] == $level) {
// 跳过
continue;
} else {
// 否则将指定字段的值相加
$result[$value['parent_id']]['total'] += $value['total'];
}
}
return array_values($result);
}
}
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!