PHP, Merging arrays with common keys

前端 未结 2 1798
借酒劲吻你
借酒劲吻你 2020-12-02 00:28

I need to get two arrays to merge into one while keeping all the keys in place and listing the values in an array like in this example:

$array1 = array(\'car         


        
相关标签:
2条回答
  • 2020-12-02 00:59
    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;
    }
    

    Usage:

    $merged = merge_common_keys($array1,$array2);
    

    PS. It can work with more than two arrays, just pass as many as you want as next arguments.

    0 讨论(0)
  • 2020-12-02 01:04

    Something like this? http://php.net/array_merge_recursive

    0 讨论(0)
提交回复
热议问题