合并具有相同键的两个关联数组

时间:2017-01-18 13:25:54

标签: php merge associative-array

我有两个数组:

$arr1 = array("123" => "abc");

$arr2 = array("123" => "xyz", "456" => "lmn");

我希望结果数组为:

$arr = array("123" => "abc,xyz", "456" => "lmn");

我知道我可以编写一些代码来获取与键对应的值,然后使用像&#39 ;;'这样的分隔符连接。或者',',但我想知道有没有有效的方法来做到这一点? 内置函数可能吗?

提前致谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

$arr1 = array("123" => "abc");

$arr2 = array("123" => "xyz", "456" => "lmn");

$o = [];
foreach($arr1 as $k => $v)
{
    $o[$k][] = $v;
}
foreach($arr2 as $k => $v)
{
    $o[$k][] = $v;
}
$result = array_map(function($v){implode(',', array_unique($v));}, $o);

答案 1 :(得分:1)

简单的foreach会做!检查内联评论

$arr1 = ["123" => "abc"];

$arr2 = ["123" => "xyz", "456" => "lmn"];

foreach ($arr2 as $key => $value) {
    if(array_key_exists($key, $arr1)) // Check if key exists in array
        $arr1[$key] .= ",$value";     // If so, append
    else
        $arr1[$key] = $value;         // otherwise, add
}

print_r($arr1);

<强>打印

Array
(
    [123] => abc,xyz
    [456] => lmn
)

选中此Eval