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?

Ken J
  • 4,312
  • 12
  • 50
  • 86

3 Answers3

5

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

Noam
  • 3,341
  • 4
  • 35
  • 64
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);
Orbling
  • 20,413
  • 3
  • 53
  • 64
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);
}
Community
  • 1
  • 1
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53