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

时间:2016-07-06 17:18:03

标签: php arrays multidimensional-array associative-array array-merge

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

1 个答案:

答案 0 :(得分:1)

$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