简体   繁体   中英

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" )) !== 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM