Jump to content

Combining 2 arrays


blinks

Recommended Posts

I have 2 arrays:

 

Array1=
([0] => Array ( [id] => 521 [countA] => 2 [dateA] => 2011-11-07 )
[1] => Array ( [id] => 647 [countA] => 5 [dateA] => 2011-12-07 )
[2] => Array ( [id] => 660 [countA] => 1 [dateA] => 2011-11-03 ))
Array2=
( [0] => Array ( [id] => 321 [countB] => 2 [dateB] => 2011-12-07 )
[1] => Array ( [id] => 645 [countB] => 5 [dateB] => 2011-11-01 )
[2] => Array ( [id] => 660 [countB] => 1 [dateB] => 2011-12-07 )) 
which I want to combine into a single array:
     
Result=
( [0] => Array ( [id] => 321 [countA] => [dateA] => [countB] => 2 [dateB] => 2011-12-07 ) 
[1] => Array ( [id] => 521 [countA] => 2 [dateA] => 2011-11-07 [countB] => [dateB] => )
[2] => Array ( [id] => 645 [countA] => [dateA] => [countB] => 5 [dateB] => 2011-11-01 )
[3] => Array ( [id] => 647 [countA] => 5 [dateA] => 2011-12-07 [countB] => [dateB] => )
[4] => Array ( [id] => 660 [countA] => 1 [dateA] => 2011-11-03 [countB] => 1 [dateB] => 2011-12-07 )) 

 

Is it possible to do this via something like array_diff, without having to loop through the arrays?

Link to comment
https://forums.phpfreaks.com/topic/264413-combining-2-arrays/
Share on other sites

Smoseley, thanks for your reply. Unfortunately array_merge doesn't do what I want, as it simply appends one array after the other.

 

Apologies for my arrays being so badly formatted and hard to read.

 

What I want to do is merge the arrays so that keys/values that exist in both arrays are retained; and where a key exists in both arrays, also retain all values in both arrays.

 

Link to comment
https://forums.phpfreaks.com/topic/264413-combining-2-arrays/#findComment-1355043
Share on other sites

Oops, missed the overlap. This'll work (though a bit sloppy):

$Result = array_filter(array_merge($Array1, $Array2), function($arr) {
    global $keys;
    $keys = is_array($keys) ? $keys : array();
    $keys[$arr['id']] = isset($keys[$arr['id']]) ? $keys[$arr['id']]+1 : 0;
    return $keys[$arr['id']] == 0;
});

Link to comment
https://forums.phpfreaks.com/topic/264413-combining-2-arrays/#findComment-1355044
Share on other sites

Ok, now I see you want to merge the child array conditionally if there's overlap.  I don't think PHP can do that without a loop.

 

Using loops, the solution is so simple!

 

$Result = array();
foreach ($Array1 as $item) $Result[$item['id']] = $item;
foreach ($Array2 as $item) $Result[$item['id']] = isset($Result[$item['id']]) ? array_merge($Result[$item['id']], $item) : $item;

 

Link to comment
https://forums.phpfreaks.com/topic/264413-combining-2-arrays/#findComment-1355048
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.