3

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
DonOfDen
  • 3,968
  • 11
  • 62
  • 112

3 Answers3

5

Alternatively, you could use a foreach in this case then merge them if they share the same id key

With using reference &

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

echo '<pre>';
print_r($array1);
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • @AresDraguna and AresDraguna Thank you.. for the help and making me understand.. The logic provided by sgt help me to get the expected output.. – DonOfDen Nov 06 '14 at 10:51
  • @AresDraguna Which answer will take less time during execution? When I accept the answer other might try and use the code so.. – DonOfDen Nov 06 '14 at 10:53
  • @TomPHP :)) how come? so if you have `array("id" => "12","name"=>"Astro")` on the 4th position in the first array and `array("id" => "7","second_name"=>"Lim"),` on the 4th position in the second one, with different id's you want to merge or map them? They have different id's!! I don't understand... – Ares Draguna Nov 06 '14 at 10:54
  • @AresDraguna if the ID is different Then the array should be just merger tot he result array... Check the Expected OutPut Array for better understanding. – DonOfDen Nov 06 '14 at 10:55
  • He wants all the elements of both array will be merged to the new array.if element in first is available will be merged, if available in second then the element of second will be merged. – Sougata Bose Nov 06 '14 at 10:57
  • Judging strictly on performance (so how fast the code will run), the second one will be faster. Judging strictly on the code logic, I will have to go with @Ghost 's answer... Because if I would have id 6 in the database and no second name and be on the 4th position in your first array and you will have id 7 and be in the 4th position on the second array with a second_name, you will give me your second name and I cannot agree with that logic – Ares Draguna Nov 06 '14 at 10:57
  • it's like mixing apples with oranges, you understand? – Ares Draguna Nov 06 '14 at 11:00
  • @AresDraguna basically this is just a lined up merging, which doesn't make sense. yeah i share your sentiment to in the case wherein if it does mess up the ordering, you'll basically merge different keys. but hey, whatever works for the OP gets accepted, right? :D – Kevin Nov 06 '14 at 11:01
  • 1
    of course... I am not judging what he wants to achieve, I am just saying that, in my point of view, the logic is wrong... I am a "purebred" PHP programmer and for me things HAVE GOT to be logic, otherwise I cannot code :)) this is one of my biggest weaknesses in life – Ares Draguna Nov 06 '14 at 11:03
3

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.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

Assign temporary first level keys to your first array to aid in identifying rows. Then loop the second array and append the desired column value to the appropriate group. Re-index the array after looping with array_values().

Code: (Demo)

$result = array_column($array1, null, 'id');
foreach ($array2 as $row) {
    $result[$row['id']]['second_name'] = $row['second_name'];
}
var_export(array_values($result));

This is a more direct approach than brute force scanning arrays with nested loops.


If all ids in the second array exist in the first array, then the following simpler line can be written inside the body of the foreach().

$result[$row['id']] += $row;
mickmackusa
  • 43,625
  • 12
  • 83
  • 136