PHP - 如何合并关联多维数组与数字键

PHP - How merge associative multidimensional arrays with numeric keys

我有 4 个数组 [$category_id => $parent_id, ...]:

$depth0 = [
    1 => 0, 
    2 => 0,
    3 => 0,
    4 => 0,
    5 => 0                      
    ];

$depth1 = [
    10 => 1,
    11 => 1,
    12 => 1,
    13 => 2,
    14 => 2,
    15 => 3,
    16 => 3
];

$depth2 = [
    17 => 11,
    18 => 11,
    19 => 11,
    20 => 13,
    21 => 13,
    22 => 14                        
];

$depth3 = [
    23 => 20,
    24 => 20
];

我需要将它们全部合并。将 $depth0 与 $depth1 合并应该给我:

1 => [10 =>[], 11=>[], 12=>[]], 
2 => [13 =>[], 14=>[]],
3 => [14=>[], 15=>[], 16=>[]],
4 => [],
5 => []

接下来是 $depth2:

1 => [10 =>[], 11=>[17=>[], 18=>[], 19=>[]], 12=>[]], 
2 => [13 =>[20=>[], 21=>[]], 14=>[]],
3 => [14=>[22=>[]], 15=>[], 16=>[]],
4 => [],
5 => []

最后是 $depth3:

$result = [
    1 => [10 =>[], 11=>[17=>[], 18=>[], 19=>[]], 12=>[]], 
    2 => [13 =>[20=>[23=>[], 24=>[]], 21=>[]], 14=>[]],
    3 => [14=>[22=>[]], 15=>[], 16=>[]],
    4 => [],
    5 => []                      
];

我想尽一切办法完成它,但没有成功,我真的没有任何其他想法,请帮助我(array_merge 不起作用)。

我想听说我很接近(我正在使用 Code Igniter - PHP 框架,不是所有的都清楚,但我认为上面的描述应该足够了):

//$categories - array with 4 SQL questions for 4 depth of categories
    private function _prepare_categories($categories) { 
        $categories_array = array();
        $empty_array = array();
        foreach ($categories as $depth => $query) {
            foreach ($query->result() as $row) {

                if($depth == 0) {
                    $categories_array[$row->ID_category] = $empty_array;
                }
                else {  
                    $categories_array = $this->multiKeyExists($categories_array, $row->ParentID, $row->ID_category);
                } 
            }

        }
        return $categories_array;
    }

    public function multiKeyExists(array $array, $parent_id, $id_category) {
        // is in base array?
        if (array_key_exists($parent_id, $array)) {
            $array[$parent_id][$id_category] = array();
            return $array;
        }
        // check arrays contained in this array
        foreach ($array as $element) {
            if (is_array($element)) {
                $new_array = $this->multiKeyExists($element, $parent_id, $id_category);
                if(!empty($new_array)) {
                    $array = array_merge($array, $element);
                    return $array;
                }
            }
        }
        return $array;
    }
$res = [];

foreach([$depth3, $depth2, $depth1, $depth0] as $depth)  
   foreach($depth as $k => $i) {
      if(isset($res[$k])) { $res[$i][$k] = $res[$k]; unset($res[$k]); }
      else $res[$i][$k] = [];
   }

print_r($res[0]);

demo