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



我有一个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
)

由于我在PHP方面的知识有限,特别是在处理SplFileObject方面,所以我想知道是否有这样一种方法,或者它真的可以做到,所以我可以收集我想要实现的数据,如上所述。

提前感谢您的帮助。

可以这样做:

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

最新更新