读取CSV到Array的特定列

时间:2016-03-02 06:38:30

标签: php fgetcsv

我正在尝试读取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);

?>

3 个答案:

答案 0 :(得分:4)

是的,您可以定义一些标记来计算行。看看下面的解决方案。它将从第5行开始打印,您也可以通过索引访问colcol。例如。对于第二列,您可以使用$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);

答案 1 :(得分:1)

您无法保证您的文件存在或您可以阅读或....

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

?>

答案 2 :(得分:0)

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

为弄清我的摘要中的数字,第5行数据位于索引[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);