在php中合并两个关联数组的问题

时间:2016-03-29 15:47:10

标签: php arrays array-merge

我在PHP中有两个数组。我在合并这两个数组时面临困难

$scheduleArray0=Array ([04/04/2016] => 
                    Array ( [TypeName_1] => Weekly
                          [TypeID_1] => 3)
                   [04/05/2016] =>
                    Array ( [TypeName_1] => Weekly 
                          [TypeID_1] => 3  ) 
                   )


 $scheduleArray1 = Array ( [04/04/2016] => 
                   Array ( [TypeName_2] => Biweekly 
                           [TypeID_2] => 7 ) 
                     [04/05/2016] =>
                  Array ( [TypeName_2] => Biweekly 
                          [TypeID_2] => 7 ) ) .

我需要它像这样合并。我的必需的输出

$final =    Array ( [04/04/2016] => 
                  Array ( [TypeName_1] => Weekly [TypeID_1] => 3 
                          [TypeName_2] => Biweekly [TypeID_2] => 7 )
               [04/05/2016] => 
                  Array ( [TypeName_1] => Weekly [TypeID_1] => 3
                          [TypeName_2] => Biweekly [TypeID_2] => 7 ) )

对于合并,我使用了以下代码

$final = merge_common_keys($scheduleArray0,$scheduleArray1);

它给了我以下多维数组。这就是我得到的

Array ([04/04/2016] => 
        Array ( [0] => Array ( [TypeName_1] => Weekly [TypeID_1] => 3 )
                [1] => Array ( [TypeName_2] => Biweekly [TypeID_2] => 7  )) 
       [04/05/2016] => 
        Array ( [0] => Array ( [TypeName_1] => Weekly [TypeID_1] => 3  ) 
                [1] => Array ( [TypeName_2] => Biweekly [TypeID_2] => 7 ) )

用户定义的函数-merco_common_keys

function merge_common_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;

}

编辑 - 当我使用array_merge()合并两个数组时,我没有在合并数组中获得$schedule_array0

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

function merge_common_keys() {
    $arrays = func_get_args();
    $result = [];

    foreach ($arrays as $array) {
        foreach ($array as $key => $value) {
            if ( ! array_key_exists($key, $result)) {
                $result[$key] = [];
            }

            $result[$key] = array_merge($result[$key], $value);
        }
    }

    return $result;
}

结果是:

enter image description here