PHP将CSV转换为特定的JSON格式 [英] PHP convert CSV to specific JSON format

查看:224
本文介绍了PHP将CSV转换为特定的JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,如下所示:

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"...

我有大约500个柱。我想将其转换为JSON,但我想要的输出看起来像:

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"
    ]
}

使用PHP ,我如何迭代通过CSV文件,这样我可以让每一列在第一行一个数组,保存在同一列中的所有其他行的值?

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?

推荐答案

这将是一个通用的方法,它适用于任何amoutn的命名colums。
如果它们是静态的,它会更短,直接解决它们。

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;

这篇关于PHP将CSV转换为特定的JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆