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,
        ),
)

 

發佈了209 篇原創文章 · 獲贊 35 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章