I have two arrays of arrays that have an id
key, and I\'d like to merge the data together based on that array\'s key and key value. The data would look somethin
Use array_replace_recursive function for easy and fast way
array_replace_recursive($color, $size)
You need to traverse all elements from both arrays one by one and merge any duplicate elements. To do this you need to perform these steps.
Glue both arrays together.
$arr = [
['id' => 1, 'color' => 'red'],
['id' => 2, 'color' => 'green'],
['id' => 3, 'color' => 'blue'],
['id' => 1, 'size' => 'SM'],
['id' => 2, 'size' => 'XL'],
['id' => 4, 'size' => 'LG'],
['id' => 3, 'size' => 'MD'],
];
Loop the combined array copying the items into a new array.
If the ID has been seen before don't append the row, but merge it with an existing one.
You can achieve all of this with a single foreach
loop and array_merge
. There is no need for recursive functions or nested loops.
// Loops on merged arrays and copied elements into a new array
foreach(array_merge($color, $size) as $el){
// If the element with this id is already in new array then add the elements together
$merged[$el['id']] = ($merged[$el['id']] ?? []) + $el;
}
The only downside is that you lose the original indexes, but it looks from your question that this was not important to you. If you want, you can reindex the array with
$merged = array_values($merged);
Live Demo
Simple nested loop would solve the purpose.
foreach($size as $key => $value1) {
foreach($color as $value2) {
if($value1['id'] === $value2['id']){
$size[$key]['color'] = $value2['color'];
}
}
}
echo '<pre>';
print_r($size);
Output:
Array
(
[0] => Array
(
[id] => 1
[size] => SM
[title] => red
)
[1] => Array
(
[id] => 2
[size] => XL
[title] => green
)
[2] => Array
(
[id] => 3
[size] => MD
[title] => blue
)
[3] => Array
(
[id] => 4
[size] => LG
)
)
Folllow this: array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value.
$combined = array_replace_recursive($color, $size);
then you can print to see the result as bellow:
print_r($combined);
Try:
$out = array();
foreach ($size as $key => $value){
if(!isset($color[$key])) { $color[$key] = array(); }
$out[] = array_merge((array)$value,(array)$color[$key]);
}
Output:
Array
(
[0] => Array
(
[id] => 1
[size] => SM
[color] => red
)
[1] => Array
(
[id] => 2
[size] => XL
[color] => green
)
[2] => Array
(
[id] => 3
[size] => MD
[color] => blue
)
[3] => Array
(
[id] => 4
[size] => LG
)
)
Better way using loop. First calculate the max array the by count this number run a loop. It will work.