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



我有 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
];

我需要将它们全部合并。将 $depth 0 与 $depth 1 合并应该给我:

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

接下来是 $depth 2:

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

最后是$depth 3:

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

正在尽一切努力做到这一点,但没有成功,我真的没有任何其他想法,请帮助我(array_merge不起作用)。

我想听到我接近了(我正在使用代码点火器 - 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]);

演示

相关内容

  • 没有找到相关文章

最新更新