Combining two arrays into a single array with a common value

I am trying to use Cobain two arrays with a key value, but I am facing some logical problem:

$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")
);

My expected input array?

$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")
);

I tried

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

My way out:

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. How can I define a key value inside a single array? or How can I bear the expected, but?

Note. I'm trying to use a value instead of a ref key: PHP Array Merge two arrays with one key

+2
source share
2 answers

You can use array_map()for this. Try it -

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);

It will generate a new array, there will be all the values ​​in both arrays. If the first element of the array is empty, then the second array will be merged and vice versa.

+3

foreach , ,

&

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

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

Source: https://habr.com/ru/post/1671003/


All Articles