0

I have a CSV file with contents that appear like so:

id     model     name     size     sizeType
100    AAA       Nike Run  11      shoe_UK
101    AAA       Nike Run  9       shoe_UK
102    AAA       Nike Run  10      shoe_UK
103    BBB       Adidas X  11      shoe_UK

I want to group models with various sizes like so:

{
   "model": "AAA",
   "name": "Nike Run",
   "sizes": [
     {
       "id": "101",
       "size": "9"
     }
     {
       "id": "102",
       "size": "10"
     }
     {
       "id": "100"
       "size": "11"
     }
   ]
     "model": "BBB",
     "name": "Adidas X",
     "sizes": [
       {
         "id": "103",
         "size": "11"
       }
    }

So far I have been able to read the CSV file using PHP and attach headers to each row of data. Unfortunately, I am not sure how to group duplicate models and sort. The eventual output will be in JSON.

<?php
/* Map Rows and Loop Through Them */
$rows   = array_map('str_getcsv', file('products.csv'));
$header = array_shift($rows);
$csv    = array();
foreach($rows as $row) {
    $csv[] = array_combine($header, $row);
}
echo json_encode($csv, JSON_PRETTY_PRINT);
?>

I would really appreciate any help!

Thank you

user4035
  • 22,508
  • 11
  • 59
  • 94
xdoey
  • 1
  • 2
  • Note that `str_getcsv` uses `,` as default delimiter. – Syscall May 08 '18 at 21:19
  • I am not sure that your CSV is correct: you can't have several files with name "model" inside a hash. Probably, you need to make an array of models. Or use the name of the model as a key. – user4035 May 08 '18 at 21:28

0 Answers0