I have a CSV file that looks like:
Name, Id, Address, Place,
John, 12, "12 mark street", "New York",
Jane, 11, "11 bark street", "New York"...
I have about 500 coloumns. I would like to convert this to JSON, but I want the output to look like:
{
"name": [
"John",
"Jane"
],
"Id": [
12,
11
],
"Address": [
"12 mark street",
"12 bark street"
],
"Place": [
"New York",
"New York"
]
}
Using PHP, how can I iterate through the CSV file so that I can make each column in the first row an array that holds the values in the same column on all the other rows?
this would be a generic method which is valid for any amoutn of named colums. if they are static, it will be shorter to address them directly
<?
$result = array();
if (($handle = fopen("file.csv", "r")) !== FALSE) {
$column_headers = fgetcsv($handle); // read the row.
foreach($column_headers as $header) {
$result[$header] = array();
}
while (($data = fgetcsv($handle)) !== FALSE) {
$i = 0;
foreach($result as &$column) {
$column[] = $data[$i++];
}
}
fclose($handle);
}
$json = json_encode($result);
echo $json;
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