Reputation: 673
I have the following csv:
title;title2;title3
test;text;text2
test1;text1;text3
I would like to convert it to associative array like:
[0]
title => test,
title2 => text
title3 => text2
[1]
title => test1,
title2 => text1
title3 => text3
i tried with :
$array = $fields = array(); $i = 0;
$handle = @fopen("file", "r");
if ($handle) {
while (($row = fgetcsv($handle, ";")) !== false) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k=>$value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
thanks
Upvotes: 0
Views: 1841
Reputation: 562
Shot in Dark: (haven't tested it)
Try below:
$array = $fields = array();
$first_array = array();
$i = 0;
if (($handle = fopen("filename", "r")) !== FALSE) {
while (($data = fgetcsv($handle, ";")) !== FALSE) {
if (empty($data)) {
continue;
}
foreach ($data as $k=>$value) {
if($i==0)
{
$first_array[$k] = $value;
}
else if(!empty($first_array))
{
$array[$i][$first_array[$k]] = $value;
}
}
$i++;
}
fclose($handle);
}
Upvotes: 0
Reputation: 8308
first, instead of using fpoen, fgetcsv, fclose you may simply use file
function , which is return your file as an array, this in case if you are dealing with small files, not a large csv file, if though this will be better to use fopen.
then you may combine it as follows :
$csvFile = file('file.csv');
// 1 - get the first element of our array
// 2 - shift it
// 3 - parse it to an array using str_getcsv
$keys = str_getcsv(array_shift($csvFile), ';');
foreach ($csvFile as $csvRecord) {
// combine our $csvRecord with $keys array
$csv[] = array_combine($keys, str_getcsv($csvRecord, ';'));
}
print_r($csv);
Upvotes: 1