如何从csv文件返回特定的行并将它们放入数组中


How to return specific rows from a csv file and put them into array

我基本上想知道如何从csv文件中获取特定的行(假设该文件有5000行,我想从第3023-3311行中获取第二列的值)。在获得这些列值后,我想将它们放入php数组中。

到目前为止我尝试过的:

 $search = $this->uri->segment(3); // get the row number    
 $row1 = 0;
   if (($handle = fopen("Folder/Data.csv", "r")) !== FALSE)
    {
        while (($data1 = fgetcsv($handle, 1000, ",")) !== FALSE)
        {
            $num1 = count($data1); // number of data rows
            $row1++;
            for ($c=0; $c < $num1; $c++) {

                echo $data1[$c+1]; // to return second row

            }
        }
        fclose($handle);

但这只返回一行,我需要返回大约200行,并将它们放入一个数组中。非常感谢您的帮助!

您非常接近。您不需要在while循环中运行for循环。你可以使用这样的东西:

$file = fopen('/path/to/file', 'r');
// Helps us keep tabs on the row we are on
$rowCount = 0;
// Array that stores all of our column values.  In this case, I'll be gathering 
// values from the second column
$secondColumnArray = array();
while(false !== ($rowData = fgetcsv($file))){
    if($rowCount >= 50 && $rowCount <= 100){
        array_push($secondColumnArray, $rowData[1]);
    }
    $rowCount = $rowCount + 1;
}
print_r($secondColumnArray);
fclose($file);

在上面的示例中,我的数组包含第二列50到100行中的值。更改参数以符合您的条件。