使用PHP根据特定方案将CSV编码为JSON

时间:2018-10-25 06:46:10

标签: php json csv highcharts logic

我有一个CSV文件:

name;categories;data
019;07:50:00;0,0
017;07:50:00;0,8
019;07:55:00;0,4
017;07:55:00;1,3
019;08:00:00;0,8
017;08:00:00;1,9

我想根据以下方案(针对Highcharts图)使用PHP将其转换为JSON文件:

{
    "xAxis": 
    {
        "categories": ["07:50:00","07:55:00","08:00:00"]
    },
    "series": 
    [
        {
        "name": "019",
        "data": [0.0,0.4,0.8]
        }, 
        {
        "name": "017",
        "data": [0.8,1.3,1.9]
        }
    ]
}

说明:

CSV文件的行与数据记录交替出现,此处为019和017(列:“名称”)。也可以有两个以上的数据记录,这不是固定的。每五分钟(列:“类别”),值就会更改(列:“数据”)。

我认为这是通过称为“控制中断”的编程方法完成的。谁能给我展示一种如何工作的方法?

2 个答案:

答案 0 :(得分:0)

实际上没有控件中断实现,因为使用数组可以进行常规检查并无需再查看“先前记录”键值。

这就是我要怎么做,

<?php

// using a data array here for illustration purposes,
// replace with reading from CSV on your own
$data = array (
  0 => 
  array (
    0 => '019',
    1 => '07:50:00',
    2 => '0,0',
  ),
  1 => 
  array (
    0 => '017',
    1 => '07:50:00',
    2 => '0,8',
  ),
  2 => 
  array (
    0 => '019',
    1 => '07:55:00',
    2 => '0,4',
  ),
  3 => 
  array (
    0 => '017',
    1 => '07:55:00',
    2 => '1,3',
  ),
  4 => 
  array (
    0 => '019',
    1 => '08:00:00',
    2 => '0,8',
  ),
  5 => 
  array (
    0 => '017',
    1 => '08:00:00',
    2 => '1,9',
  ),
);

// initialize object and properties to hold final result
$result = new stdClass();
$result->xAxis = new stdClass();
$result->series = [];
$categories = $series = [];

// accumulate data for categories and series
// using the name as key for the series array, makes it easier - otherwise you’d
// have to check if an array entry with specific name property value already exists
foreach($data as $row) {
  $categories[] = $row[1];
  $series[$row[0]][] = $row[2];
}

// make categories unique to filter out duplicates, and re-index numerically
$result->xAxis->categories = array_values(array_unique($categories));

// transform temporary series data into final structure, putting the key into the
// name property now
foreach($series as $key => $item) {
  $temp = new stdClass();
  $temp->name = $key;
  $temp->data = $item;
  $result->series[] = $temp;
}

echo json_encode($result);

(将最后一个CSV列中的x,y值转换为x.y整数格式,我也留给您。)

答案 1 :(得分:0)

这可以通过一个循环来完成,因此应该以一个循环来完成。

代码:(在本地主机上测试成功)

if (($handle = fopen("Zurreal.csv", "r")) !== false) {
    fgetcsv($handle, 1000, ';');                              // disregard column heading row
    while (($row = fgetcsv($handle, 1000, ';')) !== false) {  // notice the semicolon delimiter
        if (!isset($firstname)) {                             // if the first row of data
            $firstname = $row[0];                             // cache the name value
            $xAxis['xAxis']['categories'] = [$row[1]];        // store this row's time value
        } elseif ($firstname == $row[0]) {
            $xAxis['xAxis']['categories'][] = $row[1];        // store only time values from rows with first row's name
        }
        $series[$row[0]]['name'] = $row[0];                   // store (and overwrite after first occurrence) the name value
        $series[$row[0]]['data'][] = (float)str_replace(',', '.', $row[2]);  // push the prepared data values into the data subarray
    }
    fclose($handle);
    $result = array_merge($xAxis, ['series' => array_values($series)]);  // remove the temp keys from series and build the final array structure
    echo json_encode($result, JSON_PRETTY_PRINT);              // convert final array to json (pretty print for demo only)
}

输出:

{
    "xAxis": {
        "categories": [
            "07:50:00",
            "07:55:00",
            "08:00:00"
        ]
    },
    "series": [
        {
            "name": "019",
            "data": [
                0,
                0.4,
                0.8
            ]
        },
        {
            "name": "017",
            "data": [
                0.8,
                1.3,
                1.9
            ]
        }
    ]
}