Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgetcsv(): first row as key

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!

like image 239
fhirner Avatar asked Mar 27 '13 13:03

fhirner


People also ask

How to use fgetcsv in php?

PHP fgetcsv() Function$file = fopen("contacts. csv","r"); print_r(fgetcsv($file)); fclose($file);

How do I skip the first row in Excel using php?

skip first line or any line in csv file using php we have to add roe number $skip_row_number and pass skip row number in code. so we will check if row meach then skip row.

How do I read a csv file in column wise in php?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==

How do you check csv file is empty or not in php?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.


1 Answers

try this

while ($row = fgetcsv($handle, 256, ';')) {
    $_products[$row[0]] = array_combine($headers, $row);
}
like image 64
bipen Avatar answered Oct 03 '22 04:10

bipen