1

I've got a CSV file containing 4 fields - ID, Product Group Name, Price & Items.

The Items field is a list of products (more than one) that belong to the group, separated by a | symbol.

For example: 7, Fruit Basket, 9.99, Apple|Banana|Pear

Could you please help me to write a function to open the CSV file and output the contents as an array with the items nested at the second level.

The ID of the Product Group should be used for the key of the array.

Deniss Muntjans
  • 369
  • 10
  • 35

1 Answers1

1

This should work for you:

$result = array();
$file = fopen('data.csv', "r");
while (($row = fgetcsv($file)) !== false) {
    $id = array_shift($row);
    $row[2] = str_getcsv($row[2], "|");
    $result[$id] = $row;
}
print_r($result);

data.csv file:

7, Fruit Basket, 9.99, Apple|Banana|Pear
8, Fruit Basket, 9.99, Apple|Banana|Pear

Result:

Array
(
    [7] => Array
        (
            [0] =>  Fruit Basket
            [1] =>  9.99
            [2] => Array
                (
                    [0] =>  Apple
                    [1] => Banana
                    [2] => Pear
                )
        )
    [8] => Array
        (
            [0] =>  Fruit Basket
            [1] =>  9.99
            [2] => Array
                (
                    [0] =>  Apple
                    [1] => Banana
                    [2] => Pear
                )
        )
)

Heads up: My code works for this data structure only. If the nested items on an other position in the data, it does not work!

Timo
  • 106
  • 1
  • 4