如何在PHP中使用SplFileObject递归迭代文件?

时间:2016-09-26 15:36:29

标签: php

我有一个csv文件,其第0行的数据如下:

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

基本上,我想要实现的是将内容放在一个多维数组中,如下所示:

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
  }
}

这是我到目前为止所做的:

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

$things = [];

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

这是我得到的结果:

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] => 
)

我也尝试过:

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

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

但这就是我所得到的:

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

由于我在处理SplFileObject时对PHP的了解有限,所以我想知道是否有这样的方法或者它是否真的可以这样做,所以我可以将数据收集到我想要实现的内容中上方。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这样就可以了:

$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);