将 CSV 中的特定列读取到数组


Read specific column in CSV to Array

我正在尝试读取csv文件中的某个数据并将其传输到数组中。我想要的是获取某列的所有数据,但我想从某行开始(例如,第 5 行),有没有可能的方法可以做到这一点?我现在所拥有的只是获取特定列中的所有数据,想在第 5 行开始它,但想不出任何方法。希望你们能帮助我。谢谢!

<?php
//this is column C
$col = 2;
// open file
$file = fopen("example.csv","r");
while(! feof($file))
{
    echo fgetcsv($file)[$col];
}
// close connection
fclose($file);
?>

是的,您可以定义一些标志来计算行数。看看下面的解决方案。它将从第 5 行开始打印,您也可以通过其索引访问列。例如。对于第二列,您可以使用$row[1]

$start_row = 5; //define start row
$i = 1; //define row count flag
$file = fopen("myfile.csv", "r");
while (($row = fgetcsv($file)) !== FALSE) {
    if($i >= $start_row) {
        print_r($row);
        //do your stuff
    }
    $i++;
}
// close file
fclose($file);

您不能保证您的文件存在或可以读取它或 ....

fgets() 类似,不同之处在于 fgetcsv() 解析它以 CSV 格式读取字段的行,并返回一个包含读取字段的数组。PHP手册

//this is column C
$col = 2;
// open file
$file = fopen("example.csv","r");
if (!$file) {
    // log your error ....
}
else {
    while( ($row = fgetcsv($file)) !== FALSE){
         if (isset($row[$col])) // field doesn't exist ...
         else                   print_r ($row[$col]);
    }
}
// close file
fclose($file);
?>

根据传入数据的质量和数量,您可能希望使用迭代条件来构建输出数组,或者您可能希望将所有 csv 数据转储到主数组中,然后将其过滤为所需的结构。

为了澄清我的片段中的算术性,第 5 行数据位于索引 [4] 处。 列定位使用相同的索引 - 第 4 列位于索引 [3] 处。

一种函数式方法(假设值中没有换行符,并且没有设置任何额外的 csv 解析标志):

$starting_index = 4;
$target_column = 3;
var_export(
    array_column(
        array_slice(
            array_map(
                'str_getcsv',
                file('example.csv')
            ),
            $starting_index
        ),
        $target_column
    )
);

一种语言构造方法,其中包含基于递减计数器的前导行排除项。

$disregard_rows = 4;
$target_column = 3;
$file = fopen("example.csv", "r");
while (($row = fgetcsv($file)) !== false) {
    if ($disregard_rows) {
        --$disregard_rows;
    } else {
        $column_data[] = $row[$target_column];
    }
}
var_export($column_data);