menu

arrow_back How to combine arrays with the same keys?

by
1 vote
I have two arrays of products that have the same articles, but a different quantity, and different cities.
But there are products that do not repeat themselves.

Array
$arr1 = array(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] => 3
[brand] => Oktan
[code] => УТ-00024246
[city] => Nur-Sultan
)
)
$arr2 = array(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] => 5
[brand] => Oktan
[code] => УТ-00024246
[city] => Almaty
)
)
I need something like
$arr = array(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] =>
[0] => 3
[1] => 5
[brand] => Oktan
[code] => УТ-00024246
[city] =>
[0] => Nur-Sultan
[1] => Almaty
)
)
and the goods that do not repeat were also in a new array as usual.

1 comment

round

1 Answer

by
 
Best answer
0 votes
function merge($idKey, $mergeKeys, ...$data) {
$merged = [];

foreach (array_merge(...$data) as $item) {
$id = $item[$idKey];

if (!array_key_exists($id, $merged)) {
$merged[$id] = [
'unique' => true,
'item' => $item,
];
} else {
if ($merged[$id]['unique']) {
$merged[$id]['unique'] = false;
foreach ($mergeKeys as $k) {
$merged[$id]['item'][$k] = [ $merged[$id]['item'][$k] ];
}
}

foreach ($mergeKeys as $k) {
$merged[$id]['item'][$k][] = $item[$k];
}
}
}

return array_column($merged, 'item');
}


$merged = merge('code', [ 'quantity', 'city' ], $arr1, $arr2);