4

I have a CSV file that I need to import into an associative array. The data looks like this:

 "General Mills Cereal",http://sidom.com/dyn_li/60.0.75.0/Retailers/Saws/120914_20bp4_img_8934.jpg,$2.25,"9-17.12 oz., select varieties","Valid Sep 14, 2012 - Sep 20, 2012",Saws,"Grocery"

I wan to transform this data into an array where I can grab values like this:

 $items[$row]['title'];
 $items[$row]['imgurl'];
 $items[$row]['itemprice'];
 $items[$row]['itemsize'];
 $items[$row]['expir'];
 $items[$row]['storename'];
 $items[$row]['storetype'];

Where the elements above correspond to my CSV file. How can I import this file into such an array?

1
  • 1
    Have a look at fgetcsv Commented Sep 18, 2012 at 19:01

4 Answers 4

5

I would suggest using the built-in function fgetcsv
There's a simple usage example there also.

Sign up to request clarification or add additional context in comments.

Comments

4

fgetcsv() will give you a numerically indexed array.

Once you have read all records in to say $rawData, which has a structure along the lines of:

$rawData = array(0 => array(0 => "General Mills Cereal",
                            1 => "http://sidom.com/dyn_li/60.0.75.0/Retailers/Saws/120914_20bp4_img_8934.jpg"
                            2 => "$2.25",
                            3 => "9-17.12 oz.",
                            4 => "select varieties",
                            5 => "Valid Sep 14, 2012 - Sep 20, 2012",
                            6 => "Saws",
                            7 => "Grocery"),
                 ...);

To convert this $rawData array to what you want, you can do something like this:

$fields = array('title', 'imgurl', 'itemprice', 'itemsize',
                'expir', 'storename', 'storetype');

$data = array_map(function($cRow) uses ($fields) {
            return array_combine($fields, $cRow);
        }, $rawData);

1 Comment

Just a small correction - "uses" should be "use". Otherwise this worked for me.
3

See below URL

CSV to Associative Array

Try it

run over the csv file line by line, and insert to array like:

$array = array();
$handle = @fopen("file.csv", "r");
if ($handle) {
    while (($line = fgetcsv($handle, 4096)) !== false) {

       $array[$line[0]][$line[1]][$line[2]] = $line[3];
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

Comments

0

I´ve done this.

<?php
$file = "galerie.csv";
$handle = fopen($file, "r");
  while (($data = fgetcsv($handle)) !== FALSE) {
    $galerie[$data[0]]["alt"] = $data[1];
    $galerie[$data[0]]["caption"] = $data[2];
   }
fclose($handle);
print_r($galerie);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.