Reputation: 101
I am currently trying to use PHP to get some information from a csv file. I am using the following code and getting the following output;
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
$csvFile = '500.csv';
$csv = readCSV($csvFile);
$keys = $csv[0];
$step = $csv[1];
foreach ($step as $k=>$v)
{
$a = array("$keys[$k]");
$b = array("$v");
$c = array_combine($a, $b);
echo '<pre>';
print_r($c);
echo '</pre>';
}
and I get the output in individual arrays like;
Array
(
[first_name] => bob
)
Array
(
[last_name] => smith
)
Array
(
[company_name] => bobs logs
)
and I want the output to be in one single array, displayed like;
Array
(
[first_name] => bob
[last_name] => smith
[company_name] => bobs logs
)
If anyone could point out where I am going wrong it would be appriciated!
Upvotes: 1
Views: 86
Reputation: 1171
<?php
function readCSV($csvFile)
{
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle)) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
$csvFile = '500.csv';
$csv = readCSV($csvFile);
$keys = $csv[0];
$step = $csv[1];
$output = array();
foreach ($step as $k => $v) {
$a = array("$keys[$k]");
$b = array("$v");
$c = array_combine($a, $b);
$output = array_merge($output, $c);
}
echo '<pre>';
print_r($output);
echo '</pre>';
what changes did I make? I took outside foreach those echo and print_r and added
$output = array_merge($output, $c);
Which merge every new array as a new element inside our $output array
then finally we print $output array.
This should be working as you want, anyway if you need to change something in the future you can check array_merge function here
Upvotes: 1
Reputation: 92854
array_combine
function
Returns the combined array, FALSE if the number of elements for each array isn't equal.
Your code creates a new array on each loop iteration.
To get a single array change your loop code as shown below:
...
$c = [];
foreach ($step as $k => $v)
{
$c[$keys[$k]] = $v;
}
echo '<pre>';
print_r($c);
echo '</pre>';
Upvotes: 3
Reputation: 3795
Change:
$a = array("$keys[$k]");
$b = array("$v");
$c = array_combine($a, $b);
To:
$c[$keys[$k]] = $v;
And do this after the loop:
echo '<pre>';
print_r($c);
echo '</pre>';
Upvotes: 2