I
I
Ivan Plotnikov2022-04-15 14:36:00
PHP
Ivan Plotnikov, 2022-04-15 14:36:00

How to concatenate an array with arrays by key?

62595776973ac760437105.png
625957b11102c769751511.png
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

2 answer(s)
R
Rsa97, 2022-04-15
@the_lord_of_the_king

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

M
microbot, 2022-04-15
@microbot

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 question

Ask a Question

731 491 924 answers to any question