将两个数组合并为具有公共值的单个数组

时间:2014-11-06 10:34:59

标签: php arrays

我正在尝试Cobain两个数组值的密钥是常见的,但我面临一些逻辑问题:

$array1 = array(
    array("id" => "1","name"=>"John"),
    array("id" => "2","name"=>"Peter"),
    array("id" => "3","name"=>"Tom"),
    array("id" => "12","name"=>"Astro")
);

$array2 = array(
    array("id" => "1","second_name"=>"Lim"),
    array("id" => "2","second_name"=>"Parker"),
    array("id" => "3","second_name"=>"PHP")
);

我的预期输出数组?

$result = array(
    array("id" => "1","name"=>"John","second_name"=>"Lim"),
    array("id" => "2","name"=>"Peter","second_name"=>"Parker"),
    array("id" => "3","name"=>"Tom","second_name"=>"PHP"),
    array("id" => "12","name"=>"Astro")
);

我试过

$arraycomb = array_unique(array_merge($array1,$array2), SORT_REGULAR);

我的出局是:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John
        )

    [1] => Array
        (
            [id] => 2
            [name] => Peter
        )

    [2] => Array
        (
            [id] => 3
            [name] => Tom
        )

    [3] => Array
        (
            [id] => 12
            [name] => Astro
        )

    [4] => Array
        (
            [id] => 1
            [second_name] => Lim
        )

    [5] => Array
        (
            [id] => 2
            [second_name] => Parker
        )

    [6] => Array
        (
            [id] => 3
            [second_name] => PHP
        )

)

2。如何在同一个数组中包含键值?或者我怎样才能把预期结果拿出去?

注意:我正在尝试使用value而不是key ref:PHP Array Merge two Arrays on same key

2 个答案:

答案 0 :(得分:5)

或者,您可以在这种情况下使用foreach,然后在它们共享相同的id键时合并它们

使用参考&

foreach($array1 as &$value1) {
    foreach ($array2 as $value2) {
        if($value1['id'] == $value2['id']) {
            $value1 = array_merge($value1, $value2);
        }
    }
}

echo '<pre>';
print_r($array1);

答案 1 :(得分:3)

您可以使用array_map()。试试这个 -

function modifyArray($a, $b)
{
    if (!empty($a) && !empty($b)) {
        return array_merge($a, $b);
    } else if (!empty($a) && empty($b)) {
        return $a;
    }  else if (empty($a) && !empty($b)) {
        return $b;
    }
}

$new = array_map("modifyArray", $array1, $array2);
var_dump($new);

它将生成新数组将两个数组中的所有值。如果第一个数组的元素为空,则第二个数组将被合并,反之亦然。