PHP在特定的csv文件列中读取一个数组 [英] PHP read in specific csv file column as an array

查看:290
本文介绍了PHP在特定的csv文件列中读取一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP的新手,想要能够读取一个csv文件,该文件有两列,一个是数字(类似ID),另一个保存一个整数值。我已经查找fgetcsv函数,但我还没有找到一个方法从csv文件中读取一个特定的列。



我想获取所有的值



这样做吗?



这是我的到目前为止:

  $ file = fopen('data.csv','r'); 
$ line = fgetcsv($ file);

这是csv文件中的一些示例数据:

  ID,值
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00

任何帮助将不胜感激。 / p>

感谢。

解决方案

fgetcsv文件一次。你必须在一个循环中读取文件才能得到它:

  $ data = array(); 
while($ row = fgetcsv($ file)){
$ data [] = $ row;
}

您可以通过在循环外执行fgetcsv来跳过的标题, / trash标头值。如果你只想要第二列,你可以这样做:

  $ data [] = $ row [1] 

但是,因为你有数据,或许它可能是有用的,使用csv中的ID值键入新数组,因此也可以具有:

  $ data [$ row [0] ] = $ row [1]; 

然后你好的闪亮新数组将几乎完全匹配csv,由ID字段键入。


I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.

I would like to get all the values from the second column only, without the heading.

Any way of doing this?

This is what I have so far:

$file = fopen('data.csv', 'r');
$line = fgetcsv($file);

And this is some sample data from the csv file:

ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00

Any help would be appreciated.

Thanks.

解决方案

fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:

$data = array();
while($row = fgetcsv($file)) {
   $data[] = $row;
}

The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:

   $data[] = $row[1];

However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:

   $data[$row[0]] = $row[1];

and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.

这篇关于PHP在特定的csv文件列中读取一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆