Blogger Information
Blog 34
fans 1
comment 0
visits 57170
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组父子关联之指定key的值之和
Y的博客
Original
1747 people have browsed it
$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!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post