从csv获取关联数组

时间:2010-12-05 09:53:21

标签: php arrays csv associative-array fgetcsv

我从网址打开一个csv文件。每行有4个字段,每个字段都有一个名称:

Field1;Field2;Field3;Field4

现在我的脚本将csv数据作为一行处理,但我希望这样:

Array
(
   [0] => array(
                  ['field1'] => 1
                  ['field2'] => 2
                  ['field3'] => 3
                  ['field4'] => 4
   )
)

有什么想法吗?

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

t.csv
ID,姓名,性别,年龄
1;旭东;米; 23
2;插孔; F; 24个
3;敏杰; 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);