Answer the question
In order to leave comments, you need to log in
How to leave elements with a unique key value in a multidimensional array?
Hello!
Task:
There is an initial multidimensional array (I am attaching part of it):
$array = array (
'accessories' =>
array (
array (
'id' => 11,
'accessory_group_id' => 6,
'title' => 'Добор 2050*110*16',
'vendor_code' => '025-0079',
),
array (
'id' => 769,
'accessory_group_id' => 6,
'title' => 'Карниз Тип-3 120 см',
'vendor_code' => '025-0123',
),
array (
'id' => 768,
'accessory_group_id' => 12,
'title' => 'Добор 2050*110*16',
'vendor_code' => '025-0079',
),
array (
'id' => 3464,
'accessory_group_id' => 6,
'title' => 'Карниз Тип-3 70 см',
'vendor_code' => '025-0120',
),
array (
'id' => 3465,
'accessory_group_id' => 6,
'title' => 'Добор 2050*110*16',
'vendor_code' => '025-0079',
),
array (
'id' => 3466,
'accessory_group_id' => 6,
'title' => 'Карниз Тип-3 90 см',
'vendor_code' => '025-0122',
),
),
);
$result_array = array (
'accessories' =>
array (
array (
'id' => 11,
'accessory_group_id' => '6,12'
'title' => 'Добор 2050*110*16',
'vendor_code' => '025-0079',
),
array (
'id' => 769,
'accessory_group_id' => 6,
'title' => 'Карниз Тип-3 120 см',
'vendor_code' => '025-0123',
),
array (
'id' => 3464,
'accessory_group_id' => 6,
'title' => 'Карниз Тип-3 70 см',
'vendor_code' => '025-0120',
),
array (
'id' => 3466,
'accessory_group_id' => 6,
'title' => 'Карниз Тип-3 90 см',
'vendor_code' => '025-0122',
),
),
);
Answer the question
In order to leave comments, you need to log in
My barbaric decision in the forehead))
$array = [
'accessories' => [ /* ... Ваш массив ... */],
];
$tmp = [];
foreach ($array['accessories'] as $item) {
if (!isset($tmp[$item['vendor_code']])) {
$tmp[$item['vendor_code']] = $item;
continue;
}
$tmp[$item['vendor_code']]['accessory_group_id'] = implode(',',
array_unique(
explode(',', $tmp[$item['vendor_code']]['accessory_group_id'] . ',' . $item['accessory_group_id'])
)
);
}
$result_array['accessories'] = array_values($tmp);
var_dump($result_array);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question