anagnam
anagnam

Reputation: 457

How to recursively iterate a file using SplFileObject in PHP?

I have a csv file which has data at row 0 as follows:

Thing: Fruits
Apple
Banana
Orange
Kiwi
Thing: Furniture
Chair
Table
Bed
Rock
Thing: Planets
Earth
Sun
Mars
Thing: Insects
Ants
Mosquito
Termites
Flies

Basically, what I want to achieve is to put the contents in a multi-dimensional array like so:

array(4) {
  [0]=> Thing: Fruits(4) {
    [0]=> Apple
    [1]=> Banana
    [2]=> Orange
    [3]=> Kiwi
  }
  [1]=> Thing: Furniture(4) {
    [0]=> Chair
    [1]=> Table
    [2]=> Bed
    [3]=> Rock
  }
  [2]=> Thing: Planets(3) {
    [0]=> Earth
    [1]=> Sun
    [2]=> Mars
  }
  [3]=> Thing: Insects(4) {
    [0]=> Ants
    [1]=> Mosquito
    [2]=> Termites
    [3]=> Flies
  }
}

This is what I've done so far:

$file = new SplFileObject("test.csv");
$file->setFlags(SplFileObject::READ_CSV);

$things = [];

foreach ($file as $row) {
    $things[] = $row[0];
}
echo '<pre>';
print_r($things);

and this is the result i've got:

Array
(
    [0] => Thing: Fruits
    [1] => Apple
    [2] => Banana
    [3] => Orange
    [4] => Kiwi
    [5] => Thing: Furniture
    [6] => Chair
    [7] => Table
    [8] => Bed
    [9] => Rock
    [10] => Thing: Planets
    [11] => Earth
    [12] => Sun
    [13] => Mars
    [14] => Thing: Insects
    [15] => Ants
    [16] => Mosquito
    [17] => Termites
    [18] => Flies
    [19] => 
)

I've also tried:

foreach ($file as $row) {
    $string = $row[0];
    $find   = 'Thing';
    $pos = strpos($string, $find);

    if ($pos !== false) {
        $things[] = $row[0];
    }
}

But this is all I got:

Array
(
    [0] => Thing: Fruits
    [1] => Thing: Furniture
    [2] => Thing: Planets
    [3] => Thing: Insects
)

Due to my limited knowledge in PHP specially in dealing with SplFileObject so I want to know if there is such a way or can it really be done so I can collect the data to what I want to achieve as stated above.

Thanks in advance for your help.

Upvotes: 0

Views: 744

Answers (1)

andre
andre

Reputation: 194

This will do that:

$file = new SplFileObject("test.csv");
$file->setFlags(SplFileObject::READ_CSV);

$things = [];
$currentThingIndex = NULL;

foreach ($file as $row) {
    if($currentThingIndex === NULL || strpos($row[0], 'Thing') !== false) {
        $currentThingIndex = $row[0];
        $things[$currentThingIndex] = array();
        continue;
    }
    $things[$currentThingIndex][] = $row[0];
}
echo '<pre>';
print_r($things);

Upvotes: 1

Related Questions