Skip to content
Advertisement

Combine two arrays into a single array based on a common column value

I am trying to combine two arrays while respecting their shared value.

$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 output:

$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 have made a try by

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

My output is:

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
        )

)

How can I combine the key value inside same array? or how can I bring the expected output?

Note: I am trying for value instead of key ref: PHP Array Merge two Arrays on same key

Advertisement

Answer

You can use array_map() for this. Try this –

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 the new array will all the values in both arrays.if the first array’s element is empty then the second array will be merged and vice-versa.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement