fgetcsv(): first row as key

fhirner picture fhirner · Mar 27, 2013 · Viewed 8k times · Source

I'm building a simple shop system which takes its products from an array generated by a csv file.

My csv is as following:

pid;name;color
11149;Miro;"schwarz;weiß;blau;rot;gelb"
11004;FritzHansen;"buche;nussbau;schwarz;weiß;blau;hellblau;rot;grün;gelb;retro"

I'm using te following script

if (($handle = fopen('_products.csv', 'r')) === false) {
    die('Error opening file');
}

$headers = fgetcsv($handle, 256, ';');
$_products = array();

while ($row = fgetcsv($handle, 256, ';')) {
    $_products[] = array_combine($headers, $row);
}
fclose($handle);

which produces this array:

Array
(
    [0] => Array
        (
            [pid] => 11149
            [name] => Miro
            [color] => schwarz;weiß;blau;rot;gelb
        )

    [1] => Array
        (
            [pid] => 14215
            [name] => 1800
            [color] => schwarz;anthrazit
        )

    [2] => Array
        (
            [pid] => 11004
            [name] => FritzHansen
            [color] => buche;nussbau;schwarz;weiß;blau;hellblau;rot;grün;gelb;retro
        )
)

I want the keys 0-x to be the value of [pid] of the according "sub"-array.

How do I do this? Thanks!

Answer

bipen picture bipen · Mar 27, 2013

try this

while ($row = fgetcsv($handle, 256, ';')) {
    $_products[$row[0]] = array_combine($headers, $row);
}