Question

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!

Was it helpful?

Solution

try this

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

OTHER TIPS

This should do what you need:

$products = array();

foreach  ($_products as $product)
{
  $products[$product['pid']] = $product;
}

print_r($products);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top