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

Posted

技术标签:

【中文标题】php合并两个关联数组的问题【英文标题】:Problems in merging two associative arrays in php 【发布时间】:2016-07-17 06:55:12 【问题描述】:

我在 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 ) )

用户自定义函数-merge_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

【问题讨论】:

能否提供merge_common_keys的功能? @tommy 我已经添加了 merge_common_keys() 定义 【参考方案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;

结果是:

【讨论】:

以上是关于php合并两个关联数组的问题的主要内容,如果未能解决你的问题,请参考以下文章

PHP 将两个关联数组合并为一个数组

PHP添加重复的数组

PHP 数组中的每个ID键关联一个值,可不可以关联两个值?

数组的操作

如果两个值匹配,则从 php 中的多维关联数组中删除重复项

关联数组的合并递归问题