php - 将 JSON 转换为 Array 来绘制图表

标签 php mysql arrays json

我正在从 mysql 数据库读取值,然后通过以下代码导出到 JSON

<?php

require_once 'includes/global.inc.php';

    $query = "SELECT * FROM  `chart_sales` ORDER BY id LIMIT 0 , 100";
    $result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
    // get data and store in a json array
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $ph[] = array(
            'timestamp' => $row['timestamp'],
            'ph' => $row['ph']
          );
    }

    echo json_encode($ph);
?>

这就像一个魅力,并给我以下输出:

[{"timestamp":"1383755099000","ph":"0.50"},{"timestamp":"1383755299000","ph":"1.50"},{"timestamp":"1383755999000","ph":"1.00"}]

现在我的问题来了。我想将 JSON 值转换为数组,以便可以将数据绘制到图表中。

这是绘制图表的代码:

        var d2 = [ [1383755099000, 1], [1383755299000, 1.5], [1383755999000, 1] ];          

        var sales_charts = $('#sales-charts').css({'width':'100%' , 'height':'220px'});
        $.plot("#sales-charts", [
            { label: "pH", data: d1 },
            { label: "EC", data: d2 },
        ]

如您所见,到目前为止,我已经手动插入了 var d2 的数组。这样你就可以看到数组是如何布局的。 不幸的是,我使用 JSON 的经验很少。因此,如果您知道读取 json 文件并将其转换为可用数组的方法 - 请告诉我。

最佳答案

您可以使用以下代码将 JSON 对象转换为数组:

d2 = [{"timestamp":"1383755099000","ph":"0.50"},{"timestamp":"1383755299000","ph":"1.50"},{"timestamp":"1383755999000","ph":"1.00"}];

var result = [];
for (var i in d2) {
    result[i] = [];
    result[i]['timestamp'] = d2[i].timestamp;
    result[i]['ph'] = d2[i].ph;
}

关于php - 将 JSON 转换为 Array 来绘制图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837623/

相关文章:

php - 使用 curl php 上传缺少 POST 参数

php - 仅当另一个表中的 id 存在时才插入行

php - 将大表格发布到 php 文件

MYSQL从列中插入特定数据

c - 如何使用 int ** 而不是 int [][] 二维数组

javascript - 根据各种属性类型和值过滤数组

php - TinyMCE 中的自定义格式 div 与以前的 div 合并

mysql - 如何从 MySQL 表中的连接字段创建新记录

php - 使用链接中的查询删除mysql数据库中的记录

PHP:$_SESSION 作为数组不起作用,不允许我添加新项目?