php PHP将csv列读入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17653946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:13:20  来源:igfitidea点击:

PHP reading csv column into array

php

提问by Joseph

I there a php function that enables me to read a csv column (COLUMN NOT LINE) into an array or a string ?

我有一个 php 函数可以让我将 csv 列(COLUMN NOT LINE)读入数组或字符串?

thank you in advance.

先感谢您。

采纳答案by user2140111

May this will help. http://www.php.net/manual/de/function.fgetcsv.phpJust grab the position of the row for the column you want to have.

愿这会有所帮助。 http://www.php.net/manual/de/function.fgetcsv.php只需抓住您想要的列的行位置。

回答by Goran

$csv = array_map("str_getcsv", file("data.csv", "r")); 
$header = array_shift($csv); 
// Seperate the header from data

$col = array_search("Value", $header); 
 foreach ($csv as $row) {      
 $array[] = $row[$col]; 
}

回答by Nanhe Kumar

$arr=array();
$row = -1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);

        $row++;
        for ($c = 0; $c < $num; $c++) {
            $arr[$row][$c]= $data[$c];
        }
    }
    fclose($handle);
}

回答by deej

You should give fgetcsvmethod a try. It lets you read a file line by line and returns associative array. This function is specially for reading from CSV files.

你应该fgetcsv试试方法。它允许您逐行读取文件并返回关联数组。此功能专门用于读取 CSV 文件。

In any case you will have to read each line even if you will have to process just a column.

在任何情况下,即使您只需要处理一列,您也必须阅读每一行。

http://php.net/manual/en/function.fgetcsv.php

http://php.net/manual/en/function.fgetcsv.php