Reputation: 21
I'm trying to Read a CSV file, where the format is:
titleA,titleB,titleC
data1A,data1B,data1C
data2A,data2B,data3C
The OUTPUT expected is:
Array
(
[0] => Array
(
[titleA] => data1A
[titleB] => data1B
[titleC] => data1C
)
[1] => Array
(
[titleA] => data2A
[titleB] => data2B
[titleC] => data2C
)
I tried using something that I foound here:
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$twoDarray[] = $data;
}
fclose($handle);
}
But it shows 1 array with all the titles and other 2 Arrays with Data.
Upvotes: 2
Views: 208
Reputation: 62
You can take firslt as heading and then combine it with each row.
$heading = array();
$heading_check =1;
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($heading_check){
$heading = $data;
$heading_check=0;
continue;
}
$twoDarray[] = array_combine($heading,$data);
}
fclose($handle);
}
Upvotes: -1
Reputation: 78994
You want to read the first line and use it as the keys and combine:
if (($handle = fopen($filename, "r")) !== FALSE) {
$titles = fgetcsv($handle, 1000);
while (($data = fgetcsv($handle, 1000)) !== FALSE) {
$twoDarray[] = array_combine($titles, $data);
}
fclose($handle);
}
Upvotes: 2