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

1
  • what would be the size of the final array. equal to the first array or second array?? Commented Nov 6, 2014 at 10:50

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

9 Comments

@AresDraguna and AresDraguna Thank you.. for the help and making me understand.. The logic provided by sgt help me to get the expected output..
@AresDraguna Which answer will take less time during execution? When I accept the answer other might try and use the code so..
@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...
@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.
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
|
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.

2 Comments

this solution would only help if the ids are not important as when they get merged the ids will overlap.
Yup! I added an alternative key to have ID for reference.. Thank you!!
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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.