mrdarb mrdarb - 4 months ago 20
PHP Question

Array variable key/value PHP

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!

Answer

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>';
Comments