可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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;
回答2:
Compact solution:
<?php $fp = fopen('file.csv', 'r'); $array = array_fill_keys(array_map('strtolower',fgetcsv($fp)), array()); while ($row = fgetcsv($fp)) { foreach ($array as &$a) { $a[] = array_shift($row); } } $json = json_encode($array);
回答3:
There are a few helpful php functions that will do what you need.
Open fopen and parse with fgetcsv.
Once you have your array use *json_encode* to get it into JSON format.
Something like this might work (not tested):
$results = array(); $headers = array(); //some parts ripped from http://www.php.net/manual/en/function.fgetcsv.php if (($handle = fopen("test.csv", "r")) !== FALSE) { $line = 0; while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { for ($x=0; $x < count($data); $c++) { if ($line == 0) { $headers[] = $data[$x]; } $results[$x][] = $data[$x]; } } fclose($handle); } $output = array(); $x = 0; foreach($headers as $header) { $output[$header] = $results[$x++]; } json_encode($output);