PHP转换CSV到特定的JSON格式


PHP convert CSV to specific JSON format

我有一个CSV文件,看起来像:

Name, Id, Address, Place,
John, 12, "12 mark street", "New York",
Jane, 11, "11 bark street", "New York"...

我大约有500列。我想将其转换为JSON,但我希望输出看起来像:

{
    "name": [
        "John",
        "Jane"
    ],
    "Id": [
        12,
        11
    ],
    "Address": [
        "12 mark street",
        "12 bark street"
    ],
    "Place": [
        "New York",
        "New York"
    ]
}

使用PHP,我如何遍历CSV文件,以便我可以使第一行中的每列都成为一个数组,该数组保存所有其他行中同一列中的值?

这将是一个通用方法,对任何数量的命名列都有效。如果它们是静态的,那么直接对它们进行寻址会更短

<?
$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;

紧凑解:

<?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);

这里有一些有用的php函数可以满足你的需要。

打开fopen并使用fgetcsv解析。

一旦你有你的数组使用*json_encode*将其转换成JSON格式。

类似这样的操作可能会起作用(未测试):

$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);