开发者

Get associative array from csv

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开发者_StackOverflow中文版" )) !== 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜