PHP把列表数据的子级内容合并到父级

                                                                PHP把列表数据的子级内容合并到父级

1、父级count总和 = 父级count + 该父级下所有子级count

2、代码:

public function list(){
    $assoc = [  //定义父级ID对应的子级ID
        1 => [1, 3],
        2 => [2, 4, 5],
        6 => [6, 7, 8],
        9 => [9, 10]
    ];
    $list = [
        ['id'=>'1', 'name'=>'父级1', 'count'=>1],
        ['id'=>'2', 'name'=>'父级2', 'count'=>1],
        ['id'=>'3', 'name'=>'子级3', 'count'=>1],
        ['id'=>'4', 'name'=>'子级4', 'count'=>1],
        ['id'=>'5', 'name'=>'子级5', 'count'=>1],
        ['id'=>'6', 'name'=>'父级6', 'count'=>1],
        ['id'=>'7', 'name'=>'子级7', 'count'=>1],
        ['id'=>'8', 'name'=>'子级8', 'count'=>1],
    ];
    $ids = array_column($list, 'id');
    $listCombine = array_combine($ids, $list);

    $result = [];
    $pids = array_keys($assoc);
    foreach ($pids as $pid){
        $ids = isset($assoc[$pid]) ? $assoc[$pid] : [];    //获取父级下的子级
        foreach ($ids as $id){
            if (!isset($listCombine[$id])){
                continue;
            }
            if(isset($result[$pid])){
                $result[$pid]['count'] += $listCombine[$id]['count'];
            }else{
                $result[$pid] = $listCombine[$id];
            }
        }
    }
    return $result;
}

3、打印结果为

array (
    1 =>
        array (
            'id' => '1',
            'name' => '父级1',
            'count' => 2,
        ),
    2 =>
        array (
            'id' => '2',
            'name' => '父级2',
            'count' => 3,
        ),
    6 =>
        array (
            'id' => '6',
            'name' => '父级6',
            'count' => 3,
        ),
)
发布了223 篇原创文章 · 获赞 36 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/104031537