Answer the question
In order to leave comments, you need to log in
How to concatenate an array with arrays by key?
How to merge two arrays with arrays so that the result is a third array? Merge by key "product".
$array = [
0 => [
'product' => 'Мирт в стеклянном цилиндре',
'local_link' => 'localhost/catalog/mirt-v-steklyannom-tsilindre',
'remote_link' => '/item/mirt-v-steklyannom-tsilindre'
],
1 => [
'product' => 'Панно прозрачное с синим Лимониумом',
'local_link' => 'localhost/catalog/panno-prozrachnoe-s-sinim-limoniumom',
'remote_link' => '/item/panno-prozrachnoe-s-sinim-limoniumom'
]
];
Answer the question
In order to leave comments, you need to log in
$localKeys = array_column($arr1, 'product');
$remoteKeys = array_column($arr2, 'product');
$totalKeys = array_values(array_unique(array_merge($localKeys, $remoteKeys)));
$localLinks = array_combine(
$localKeys,
array_column($arr1, 'local_link')
);
$remoteLinks = array_combine(
$remoteKeys,
array_columns($arr2, 'remote_link')
);
$result = array_map(
fn($key) => [
'product' => $key,
'local_link' => $localLinks[$key] ?? null,
'remote_link' => $remoteLinks[$key] ?? null
]
);
The result is not very optimal code and, perhaps, it is similar to yours
$test = $collect
->groupBy('product')->map(function ($item) {
return $item[0];
})->toArray();
$test_2 = $collect_2
->groupBy('product')->map(function ($item) {
return $item[0];
})->toArray();
foreach ($test as $key => $item) {
$test_3[$key] = array_merge($test[$key] ?? [], $test_2[$key] ?? []);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question