I've created a import script to convert a spreadsheet containing vehicle makes and models into related database entities. My source array from the spreadsheet looks like this (each is a spreadsheet row):
$rows = [
['Brand A', 'Model A'],
['Brand A', 'Model A'],
['Brand A', 'Model B'],
['Brand A', 'Model B'],
['Brand A', 'Model B'],
['Brand A', 'Model C'],
['Brand B', 'Model A'],
['Brand B', 'Model B'],
['Brand B', 'Model B'],
['Brand B', 'Model B'],
['Brand B', 'Model C'],
['Brand B', 'Model C'],
];
I want this data in this format:
$data = [
'Brand A' => [
'Model A',
'Model A',
'Model B',
'Model B',
'Model B',
'Model C',
],
'Brand B' => [
'Model A',
'Model B',
'Model B',
'Model B',
'Model C',
'Model C',
],
];
I have a working example using a foreach loop:
$data = [];
foreach ($rows as $row) {
$data[strval($row[0])][] => strval($row[1]);
}
I'd like to use one of the PHP array functions if possible. I've tried the following but it's not creating the brand name indexes:
$data = array_map(function ($row) {
return $data[strval($row[0])][] = strval($row[1]);
}, $rows);
The array ends up as follows:
$data = [
'Model A',
'Model A',
...
];
Is this possible or am I wasting my time/over engineering this?
PT 2: Bonus points for making the models unique for a brand at the same time.
$data = [
'Brand A' => [
'Model A',
'Model B',
'Model C',
],
'Brand B' => [
'Model A',
'Model B',
'Model C',
],
];