【问题标题】:PHP convert CSV to specific JSON formatPHP 将 CSV 转换为特定的 JSON 格式
【发布时间】:2013-06-13 20:33:11
【问题描述】:

我有一个 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 它。
  • 循环列表,附加到组$output["name"][] = $row[0];。如果您需要进一步的建议,请展示您当前的尝试。

标签: php json parsing csv


【解决方案1】:

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

<?
$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】:

    紧凑的解决方案:

    <?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】:

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

      【讨论】:

        猜你喜欢
        • 2020-11-06
        • 2019-02-01
        • 1970-01-01
        • 2016-02-12
        • 1970-01-01
        • 2021-10-29
        • 1970-01-01
        • 2016-11-06
        相关资源
        最近更新 更多