【问题标题】:PHP convert CSV to specific JSON distributionPHP 将 CSV 转换为特定的 JSON 分布
【发布时间】:2018-12-21 15:15:48
【问题描述】:

我有一个将 CSV 转换为 JSON 的 PHP 文件,但我希望输出 JSON 具有与我现在得到的不同的“层次结构”(见下文)。

我的 CSV 文件看起来像这样:

Icon Name, Responses, Performance  
03_v10_Assembly_point, 225, 38  
55_v10_Fire, 203, 87  
23_v10_Warning_volcano, 324, 79
      

我希望输出的 JSON 看起来像这样:

{
    "03_v10_Assembly_point" {
            "Responses": "225",
            "Performance": "38"
    },
    "55_v10_Fire" {
            "Responses": "203",
            "Performance": "87"
    },
    "23_v10_Warning_volcano" {
            "Responses": "324",
            "Performance": "79"
    }
}

或类似的,重要的是将第一列作为其他参数的“标题”。

有没有办法做到这一点? :(

2018 年 12 月 22 日更新

虽然问题已经得到解答,但这是我得到的原始 JSON 输出:

[
    {
        "Icon": "03_v10_Assembly_point",
        "Responses": "225",
        "Performance": "38",
        "id": 0
    },
    {
        "Icon": "55_v10_Fire",
        "Responses": "203",
        "Performance": "87",
        "id": 1
    },
    {
        "Icon": "23_v10_Warning_volcano",
        "Responses": "324",
        "Performance": "79",
        "id": 2
    }
]

【问题讨论】:

  • 是的,有办法做到这一点。你有什么尝试?请发布您的代码。
  • 您还应该在问题本身中包含您当前遇到的问题,而不是作为场外链接。当该链接发生变化时,这个问题对未来的访问者来说意义不大。

标签: php json csv


【解决方案1】:

您必须逐行读取 csv 文件。我跳过了第一行,因为在你的情况下我们不需要它。

<?php   
$file = fopen('file.csv', 'r'); //read the csv file. Change file.csv to your current file
$i = 0; //initialize $i
$new_arr = array(); //initialize $new_arr
while (($line = fgetcsv($file)) !== FALSE) { //Read each line of the file
    if($i != 0){ //Check if we are on the first line or not
        $new_arr[$line[0]] = array("Responses" => $line[1], "Performance" => $line[2]); //Save info from csv into the new array
    }
    $i++; //Increment by one to escape only the first line
}
fclose($file); //Close file
echo json_encode($new_arr); //Encode result as json and make an echo

输出:

{  
   "03_v10_Assembly_point":{  
      "Responses":" 225",
      "Performance":" 38 "
   },
   "55_v10_Fire":{  
      "Responses":" 203",
      "Performance":" 87 "
   },
   "23_v10_Warning_volcano":{  
      "Responses":" 324",
      "Performance":" 79"
   }
}

【讨论】:

  • 工作完美!
【解决方案2】:
$result = [];

$data = array_slice(array_map('str_getcsv', file('file.csv')), 1); # read csv, skip header

foreach ($data as list($index, $responses, $performance))
{
    $result[$index] = ['Responses' => trim($responses), 'Performance' => trim($performance)];
}

$result = json_encode($result);

【讨论】:

    【解决方案3】:

    警告!这仅在 csv 没有任何包含换行符、逗号或被引号包围的值时才有效

    也许这不是最好的使用方法,但它显示了您如何做到这一点。

    // Delete first line, and load file using file_get_contents to $csv var
    $csv = '03_v10_Assembly_point, 225, 38' . PHP_EOL .
    '55_v10_Fire, 203, 87' . PHP_EOL . 
    '23_v10_Warning_volcano, 324, 79';
    
    $csv_file = explode(PHP_EOL , $csv);
    foreach($csv_file as $line) {
        $csv_array = explode("," , $line);
    
        $json_key = trim($csv_array[0]);
    
        $json[$json_key] = [
            'Responses' => trim($csv_array[1]),
            'Performance' => trim($csv_array[2])
        ];
    
    }
    
    print_r($json);
    
    // now create json
    $json = json_encode( $json );
    

    结果是

    Array
    (
        [03_v10_Assembly_point] => Array
            (
                [Responses] =>  225
                [Performance] =>  38
            )
    
        [55_v10_Fire] => Array
            (
                [Responses] =>  203
                [Performance] =>  87
            )
    
        [23_v10_Warning_volcano] => Array
            (
                [Responses] =>  324
                [Performance] =>  79
            )
    
    )
    
    {"03_v10_Assembly_point":{"Responses":" 225","Performance":" 38"},"55_v10_Fire":{"Responses":" 203","Performance":" 87"},"23_v10_Warning_volcano":{"Responses":" 324","Performance":" 79"}}
    

    【讨论】:

    • 这不是在 PHP 中读取/解析 CSV 的好方法。如果有一些列/值包含换行符,它会弄乱你的结果。你应该改用fgetcsv()
    • 是的,我同意,但是如果他需要做得更好,他应该使用一些使用@executable方式的csv文件解析器类或函数。
    • 如果您同意,为什么要发布这个作为答案?
    • 因为这也是这个问题的答案。他的数据很简单,所以我的方法应该很有效:-) 我不建议将它用于更复杂的 csv。
    • 我们不知道 CSV 来自哪里,也不知道它明天是否会发生变化,因此您应该始终建议最佳实践代码。故意暗示不良做法对每个人都不利。特别是在答案中没有任何注释/警告。
    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 2012-03-23
    • 2019-05-18
    • 2020-11-06
    • 2019-02-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多