I have two 2D arrays. They both contain id and other, not so-related, stuff. My job is to merge those two arrays together if id's match!
This is how they look:
array(3) {
[0]=>
array(3) {
["id"]=>
string(3) "161"
["x"]=>
string(1) "foo"
["y"]=>
string(1) "bar"
}
}
[1]=>
array(3) {
["id"]=>
string(3) "164"
["x"]=>
string(1) "foo"
["y"]=>
string(1) "bar"
}
[2]=>
array(3) {
["id"]=>
string(3) "168"
["x"]=>
string(1) "foo"
["y"]=>
string(1) "bar"
}
}
array(2) {
[0]=>
array(3) {
["id"]=>
string(3) "161"
["z"]=>
string(1) "baz"
}
[1]=>
array(3) {
["id"]=>
string(3) "164"
["z"]=>
string(1) "baz"
}
And this is how result should look:
array(3) {
[0]=>
array(3) {
["id"]=>
string(3) "161"
["x"]=>
string(1) "foo"
["y"]=>
string(1) "bar"
["z"]=>
string(1) "baz"
}
}
[1]=>
array(3) {
["id"]=>
string(3) "164"
["x"]=>
string(1) "foo"
["y"]=>
string(1) "bar"
["z"]=>
string(1) "baz"
}
[2]=>
array(3) {
["id"]=>
string(3) "168"
["x"]=>
string(1) "foo"
["y"]=>
string(1) "bar"
}
}
And this is what I have so far. Of course, it doesn't work.
foreach ($rated_items as $item) {
foreach ($posts as $post) {
if ($post['id'] == $item['id']) {
$posts = array_merge($posts, $item); // Doesn't work at all.
}
}
}
The problem is that I don't know how to merge current $post to current $item and then, both of them, add to $posts array without getting duplicates.
Thanks in an advice!