将CSV转换为特定的JSON格式的PHP代码

3

我有一个看起来像这样的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文件,以便将第一行中的每一列都变为一个数组,其中包含所有其他行中相同列中的值?

我会使用file_get_contents来加载CSV文件,然后使用explode(",", $csvfile)将其拆分为数组,然后对数组进行操作,直到达到你想要的样子,最后使用json_encode将其转换为JSON格式。 - SSH This
循环遍历列表,将其附加到组 $output["name"][] = $row[0];。如果需要进一步建议,请展示您当前的尝试。 - mario
3个回答

5

这将是一种通用的方法,适用于任何数量的命名列。如果它们是静态的,直接引用它们会更短。

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

0

有一些有用的 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);

0

简洁的解决方案:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接