将csv转换为keyed json

时间:2017-03-02 13:12:14

标签: php json csv

我的csv文件包含如下所示的数据而没有列标题

100271311,90445XXXX,Active
100271400,99456XXXX,Cancelled
100271552,94280XXXX,Pending

我想将上面的内容转换为php json输出,如下所示

{
   "100271311": {
      "FIELD2": "90445XXXX",
      "FIELD3": "Active"
   },
   "100271400": {
      "FIELD2": "99456XXXX",
      "FIELD3": "Cancelled"
   },
   "100271552": {
      "FIELD2": "94280XXXX",
      "FIELD3": "Pending"
   }
}

请帮助

4 个答案:

答案 0 :(得分:0)

你可以试试这个:

$file  = "csvfile.csv";
$csv   = file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json  = json_encode($array);
print_r($json);

注意: str_getcsv为CSV格式的字段解析字符串输入,并返回包含读取字段的数组。

答案 1 :(得分:0)

你可以尝试一下:

  $file = file('pathtoyour/file.csv');
  $json = [];
  foreach ($file as $key => $row) {
    $cols = explode(',', $row);
    $json[trim($cols[0])] = [
      'FIELD2' => trim($cols[1]),
      'FIELD3' => trim($cols[2]),
    ];
  }
  die(json_encode($json));

答案 2 :(得分:0)

使用fileexplodejson_encode函数的解决方案:

$lines = file("./data/test.csv");  // change with your actual file path
$result = [];

foreach ($lines as $line) {
    list($k, $f2, $f3) = explode(',', $line);
    $result[$k] = ['FIELD2' => $f2, 'FIELD3' => trim($f3)];
}

print_r(json_encode($result, JSON_PRETTY_PRINT));

输出:

{
    "100271311": {
        "FIELD2": "90445XXXX",
        "FIELD3": "Active"
    },
    "100271400": {
        "FIELD2": "99456XXXX",
        "FIELD3": "Cancelled"
    },
    "100271552": {
        "FIELD2": "94280XXXX",
        "FIELD3": "Pending"
    }
}

答案 3 :(得分:0)

您可以使用此站点将csv转换为键控JSON。

https://www.convertcsv.com/csv-to-json.htm

有很多转换方法。只需选择转换类型按钮即可。