得到CSV关联数组 [英] Get associative array from csv
本文介绍了得到CSV关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我打开从URL csv文件。每行有4个领域,每个领域都有一个名字:
字段1,字段2,字段3,字段4
现在我的脚本处理CSV数据作为一个单一的线,但我想有这种方式:
阵列
(
[0] =>阵列(
['field1的'] => 1
['字段2'] => 2
['FIELD3'] => 3
['field4中'] => 4
)
)
任何想法?
下面是我的code:
IF(($处理=的fopen($ EURL,R))!== FALSE){
而(($数据= fgetcsv($处理,4096,))==假的!){
$ NUM =计数($的数据);
为($ C = 0; $ C< $ NUM $ C ++){
回声$数据[$ C];
}
}
FCLOSE($处理);
}
解决方案
t.csv结果
ID,姓名,性别,年龄结果
1;徐东;米; 23结果
2;插孔; F; 24结果
3;敏杰; F; 25搜索结果
< PHP
$ EURL =t.csv;
如果(($处理=的fopen($ EURL,R))!== FALSE){
$键= fgetcsv($处理,4096,;);
而(($数据= fgetcsv($处理,4096,))==假的!){
$水库[] = array_combine($键,$数据);
}
FCLOSE($处理);
}
后续代码var_dump($水库);
I open a csv file from a url. Each line has 4 fields and each field has a name:
Field1;Field2;Field3;Field4
Now my script handles the csv data as one single line but I want to have it this way:
Array
(
[0] => array(
['field1'] => 1
['field2'] => 2
['field3'] => 3
['field4'] => 4
)
)
Any ideas?
Here is my code:
if (($handle = fopen ( $eurl, "r" )) !== FALSE) {
while ( ($data = fgetcsv ( $handle, 4096, ";" )) !== FALSE ) {
$num = count ( $data );
for($c = 0; $c < $num; $c ++) {
echo $data [$c];
}
}
fclose ( $handle );
}
解决方案
t.csv
id;name;sex;age
1;xudong;m;23
2;jack;f;24
3;minjie;f;25
<?php
$eurl = "t.csv";
if (($handle = fopen ( $eurl, "r" )) !== FALSE) {
$keys = fgetcsv ( $handle, 4096, ";" );
while ( ($data = fgetcsv ( $handle, 4096, ";" )) !== FALSE ) {
$res[] = array_combine($keys, $data);
}
fclose ($handle);
}
var_dump($res);
这篇关于得到CSV关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文