I have an associative array containing some keys like ([0-50], [50-100]) and their respective values like 23, 443.
I want to generate a CSV format file in which I want to have two columns like Distance and Trips. And the keys which are in array must be in the column of Distance and the values which are in the array must be in the column of Trips.
I have tried this using fputcsv() but it is not responding correctly.
<?php
$file = fopen("/tmp/abc.csv", 'w');
fputcsv($file, array(
'Distance', 'Trips'
));
foreach($ed as $k=>$v) {
fputcsv($file, $v);
}
fclose($file);
$ed response is this .
Array
(
[0-50] => 880
[50-100] => 5
[100-150] => 1
[550-600] => 1
)
fputcsv expects an array of values like:
$ed = array("val1", "val2", "val3", ... );
You are passing a value at a time in fputcsv($file, $val); which won't work or give unexpected results.
In order to get the values of your array, do the following:
foreach($ed as $k=>$v) {
$row = array ( $k, $v );
fputcsv($file, $row);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With