PHP CSV for associative array

I have a CSV file that I need to import into an associative array. The data is as follows:

"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 want to convert this data to an array, where I can get these values:

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

If the items above match my CSV file. How to import this file into such an array?

+4
source share
3 answers

I would suggest using the built-in fgetcsv function
There is a simple usage example.

+5
source

fgetcsv() will give you a numerical index array.

Once you read all the entries to say $rawData , which has a structure in lines:

 $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 the $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); 
+4
source

See URL below

CSV for associative array

Try

run the csv file line by line and paste into the array as:

 $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); } 
+3
source

Source: https://habr.com/ru/post/1434923/


All Articles