need to define a function that create a associative array from csv file(data as below) using only php code (no jquery and mysql)
using foreachloop
id | img | title | desc | price |
12 | abc.jpg | machine1 | description1 | 25 |
13 | bsc.jpg | machine2 | description2 | 25 |
14 | fgb.jpg | machine3 | description3 | 25 |
Expert Answer
Hello,
CSV is coma seperated value, You can simply create an associative array form csv file using only php
there are several ways , i mean this is an example
<?php
$array = $fields = array(); $i = 0; // declar $array and $fields as array , fields means header
$handle = @fopen(“testcsv.csv”, “r”); // open the csv file
if ($handle) {
while (($row = fgetcsv($handle, 4096)) !== false) { // condition for while
if (empty($fields)) {
$fields = $row;
continue; // to skip first field ie the header
}
foreach ($row as $k=>$value) { // $value gives the value
$array[$i][$fields[$k]] = $value; // we set $k as value so that the index will be the field
}
$i++;
}
if (!feof($handle)) { // errror
echo “Error: unexpected fgets() failn”;
}
fclose($handle); // close the file operation
}
echo “The total array<br/>”;
var_dump($array);
echo “<br/>Your Header<br/>”;
var_dump($fields);
?>
this will o/p as
now take the value as you want
this will also work
<?php
/* Map Rows and Loop Through Them */
$rows = array_map(‘str_getcsv’, file(‘testcsv.csv’));
$header = array_shift($rows);
$csv = array();
foreach($rows as $row) {
$csv[] = array_combine($header, $row);
}
var_dump($csv);
?>