Answer the question
In order to leave comments, you need to log in
How to join two multidimensional arrays?
There are two arrays:
$products and
$attributes
The arrays contain the same number of elements. They can be up to 500,000 eaten.
It is necessary to combine them into one array, so that later you can work with it. They have a linking element: product_id
**Array of products**
$products = array(
[0] = array(
[product_id] => 102966
[price] => 11
)
[1] = array(
[product_id] => 102967
[price] => 22
)
)
$attributes= array(
[0] = array(
[product_id] => 102966
[attr_name] => Диагональ;Длительность ролика
[attr_value] => 2";1 мин, 2 мин, 3 мин, 5 мин
)
[1] = array(
[product_id] => 102967
[attr_name] => Выходы;Диагональ;Дополнительная информация
[attr_value] => HDMI;2.7";рабочие диапазоны
)
)
Answer the question
In order to leave comments, you need to log in
The solution is "on the forehead", but it will work
$products = [
[
'product_id' => 102966,
'price' => 11,
],
[
'product_id' => 102967,
'price' => 22,
]
];
$attributes = [
[
'product_id' => 102966,
'attr_name' => 'Диагональ;Длительность ролика',
'attr_value' => '2";1 мин, 2 мин, 3 мин, 5 мин',
],
[
'product_id' => 102967,
'attr_name' => 'Выходы;Диагональ;Дополнительная информация',
'attr_value' => 'HDMI;2.7";рабочие диапазоны',
],
];
$products = array_map(function($product) use ( $attributes ) {
$attribute = array_filter($attributes, function($attribute) use ( $product ) {
return $attribute['product_id'] === $product['product_id'];
});
return array_merge($attribute ? current($attribute) : [], $product);
}, $products);
print_r($products);
As an option, convert both arrays to associative ones with product_id as a key, and then run through the second array and add missing elements or individual attributes to the first one, if there are elements themselves. O(N) + O(M) complexity, N+M memory overhead
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question