简体   繁体   中英

Parse csv to associative array php with ; delimiter

I have the following csv:

title;title2;title3
test;text;text2
test1;text1;text3

I would like to convert it to associative array like:

[0]
title => test,
title2 => text
title3 => text2
[1]
 title => test1,
title2 => text1
title3 => text3

i tried with :

    $array = $fields = array(); $i = 0;
$handle = @fopen("file", "r");
if ($handle) {
    while (($row = fgetcsv($handle, ";")) !== false) {
        if (empty($fields)) {
            $fields = $row;
            continue;
        }
        foreach ($row as $k=>$value) {
            $array[$i][$fields[$k]] = $value;
        }
        $i++;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

thanks

first, instead of using fpoen, fgetcsv, fclose you may simply use file function , which is return your file as an array, this in case if you are dealing with small files, not a large csv file, if though this will be better to use fopen.

then you may combine it as follows :

$csvFile = file('file.csv');

// 1 - get the first element of our array
// 2 - shift it
// 3 - parse it to an array using str_getcsv
$keys = str_getcsv(array_shift($csvFile), ';');
foreach ($csvFile as $csvRecord) {
    // combine our $csvRecord with $keys array
    $csv[] = array_combine($keys, str_getcsv($csvRecord, ';'));
}

print_r($csv);

Shot in Dark: (haven't tested it)

Try below:

$array = $fields = array();
$first_array = array();
$i = 0;
if (($handle = fopen("filename", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, ";")) !== FALSE) {

        if (empty($data)) {
            continue;
        }

        foreach ($data as $k=>$value) {
            if($i==0)
            {
                $first_array[$k] = $value;
            }
            else if(!empty($first_array))
            {
                $array[$i][$first_array[$k]] = $value;
            }
        } 
        $i++;   
    }
    fclose($handle);
}

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