When I apply the following piece of code for a .csv
file containing contents: WaterMelon,BlueBerry,BlackBerry
, I get the output: Array ( [0] => WaterMelon, [1]=>BlueBerry, [2]=>BlackBerry )
The output I have got is a simple array, because I had stored simple values into the .csv
file.
QUESTION:-
But what if I want to store key-value pairs
in a .csv file, and then get the output like: Array ( [FruitOne] => WaterMelon, [FruitTwo]=>BlueBerry, [FruitThree]=>BlackBerry )
How can I do that?
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line); //check. print_r() returns an array in human readable form.
}
fclose($file);
A CSV file can and many times does have a header row. So you could use this to read the first line and then use array_combine
:
$headers = fgetcsv($file);
while (($line = fgetcsv($file)) !== FALSE) {
print_r(array_combine($headers, $line));
}
Use the same concept when creating the CSV file to add the headers.
Alternately, just define $headers
yourself and use the same loop and array_combine
:
$headers = array('FruitOne', 'FruitTwo', 'FruitThree');
Try something like this:
<?php
function getArrayFromCsv($file) {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($lineArray = fgetcsv($handle)) !== FALSE) {
$dataArray[$lineArray[0]] = $lineArray[1];
}
fclose($handle);
}
return $dataArray;
}
?>