0

Is this iteration key by key the proper way of initializing custom named keys for my str_getcsv array values ? Also is the unset() expensive or even necessary in this loop ?

<?php

$lines = file('csv/random.csv', FILE_IGNORE_NEW_LINES);

foreach ($lines as $key => $value)
{

        $temp = str_getcsv($value,'|');
        $csv[$key]['code'] = $temp[0];
        $csv[$key]['name'] = $temp[1];
        $csv[$key]['price'] = $temp[2];
        $csv[$key]['avail'] = $temp[3];
        unset ($temp);   
}
?>

EDIT:

Following the advice in comments the code looks neater and runs significantly faster now

$keys = Array('code','name','price','avail');
$file = fopen('csv/random.csv',"r");
            while(! feof($file))
            {
                $temp[] = array_combine($keys,fgetcsv($file,'1000','|'));
            }
            fclose($file);

The answer marked below is I believe a more professional implementation of this for those who have need of such.

Thanks guys.

4

1 回答 1

1

You might want to use SplFileObject class:

<?php

$file = new SplFileObject('csv/random.csv');
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY
    | SplFileObject::DROP_NEW_LINE | SplFileObject::READ_AHEAD);
$file->setCsvControl('|');
$data = array();

foreach ($file as $row) {
    $data[] = array_combine(array('code', 'name', 'price', 'avail'), $row);
}

You have to be sure that your CSV lines have 4 different fields to use array_combine() this way. Note that this will give you all your CSV fields as strings. If you want, for instance, to have code as integer, name as string, price as float and avail as integer for each row, you can replace the foreach with that:

foreach ($file as $row) {
    $data[] = array_combine(
        array('code', 'name', 'price', 'avail'),
        array((int) $row[0], $row[1], (float) $row[2], (int) $row[3])
    );
}

To apply int/float conversions you can even use the fscanf() method to read lines:

<?php

$file = new SplFileObject('csv/random.csv');
$file->setFlags(SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE 
    | SplFileObject::READ_AHEAD);
$data = array();

while ($row = $file->fscanf('%d|%[^|]|%f|%d')) {
    $data[] = array_combine(array('code', 'name', 'price', 'avail'), $row);
}
于 2013-11-08T02:39:09.233 回答