合并两个关联数组,在按键碰撞期间不会丢失元素

问题描述 投票:0回答:6

在一个软件中,我使用

array_merge
函数合并两个数组。但我需要将相同的数组(当然具有相同的键)添加到现有数组中。

问题:

 $A = array('a' => 1, 'b' => 2, 'c' => 3);
 $B = array('c' => 4, 'd'=> 5);
 
 array_merge($A, $B);

 // result
 [a] => 1 [b] => 2 [c] => 4 [d] => 5

如您所见,错过了

'c' => 3

那么我怎样才能用相同的键合并所有呢?

php arrays associative-array array-merge
6个回答
55
投票

您需要使用

array_merge_recursive
而不是
array_merge
。当然,数组中只能有一个等于
'c'
的键,但关联的值将是一个同时包含
3
4
的数组。


44
投票

尝试使用 array_merge_recursive

$A = [
  'a' => 1,
  'b' => 2,
  'c' => 3,
];

$B = [
  'c' => 4,
  'd'=> 5,
];

$c = array_merge_recursive($A,$B);

echo "<pre>";
print_r($c);
echo "</pre>";

会回来

Array
(
    [a] => 1
    [b] => 2
    [c] => Array
        (
            [0] => 3
            [1] => 4
        )

    [d] => 5
)

7
投票
$arr1 = array(
   "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
   "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
   "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
   "3" => array("fid" => 1, "tid" => 7, "name" => "Xi"),
   "4" => array("fid" => 2, "tid" => 9, "name" => "Xigua")
);

如果您想按如下方式转换此数组:

$arr2 = array(
   "0" => array(
          "0" => array("fid" => 1, "tid" => 1, "name" => "Melon"),
          "1" => array("fid" => 1, "tid" => 4, "name" => "Tansuozhe"),
          "2" => array("fid" => 1, "tid" => 6, "name" => "Chao"),
          "3" => array("fid" => 1, "tid" => 7, "name" => "Xi")
    ),

    "1" => array(
          "0" =>array("fid" => 2, "tid" => 9, "name" => "Xigua")
     )
);

所以我的回答是这样的:

$outer_array = array();
$unique_array = array();
foreach($arr1 as $key => $value)
{
    $inner_array = array();

    $fid_value = $value['fid'];
    if(!in_array($value['fid'], $unique_array))
    {
            array_push($unique_array, $fid_value);
            unset($value['fid']);
            array_push($inner_array, $value);
            $outer_array[$fid_value] = $inner_array;


    }else{
            unset($value['fid']);
            array_push($outer_array[$fid_value], $value);

    }
}
var_dump(array_values($outer_array));

希望这个答案能对某人有所帮助。


3
投票
 $A = array('a' => 1, 'b' => 2, 'c' => 3);
 $B = array('c' => 4, 'd'=> 5);
 $C = array_merge_recursive($A, $B);
 $aWhere = array();
 foreach ($C as $k=>$v) {

    if (is_array($v)) {
        $aWhere[] = $k . ' in ('.implode(', ',$v).')';
    }
    else {
        $aWhere[] = $k . ' = ' . $v;
    }
 }
 $where = implode(' AND ', $aWhere);
 echo $where;

3
投票

我刚刚写了这个函数,它应该可以满足你的需要,但它确实是左连接

public function mergePerKey($array1,$array2)
    {
        $mergedArray = [];

        foreach ($array1 as $key => $value) 
        {
            if(isset($array2[$key]))
             {
               $mergedArray[$value] = null;

               continue;
             }
            $mergedArray[$value] = $array2[$key];
        }

        return $mergedArray;
    }

-1
投票

数组中的两个条目不能共享密钥,您需要更改重复项的密钥

© www.soinside.com 2019 - 2024. All rights reserved.