O
O
Oleg2018-07-17 18:03:09
PHP
Oleg, 2018-07-17 18:03:09

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
       )
    )

**Array of attributes**
$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";рабочие диапазоны
       )
    )

Tell me how to combine them taking into account so that it does not work too long and does not eat up all the memory

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pushkarev, 2018-07-17
@bysobi

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);

S
SagePtr, 2018-07-17
@SagePtr

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 question

Ask a Question

731 491 924 answers to any question