多维数组json_encoded

时间:2015-06-14 18:26:30

标签: php arrays json multidimensional-array

我尝试将每个日期和收入的多维数组作为JSon数组返回,以便在我的面板仪表板中显示图表。不幸的是,当我不对我的JSon数据进行硬编码时,图表会产生一些问题,因此我现在正在调试它,我想知道为什么我的json_encoded数组看起来很奇怪。

这是我的Panel,它绘制图表并从data.php中请求数据:

jQuery.getJSON("data.php", { request: "revenues" }, function (result) {
    var revenues = result["amount"];
    alert(revenues);
    $(".monthly-sales").sparkline(revenues, {
        type: 'bar',
        barColor: '#ff4e50',
        height: '55px',
        width: '100%',
        barWidth: 8,
        barSpacing: 1
    });
});

data.php:

elseif($request == "revenues"){
    // Output Revenues per day from nexus store
    $revenues = array();
    $revenues["dates"] = array();
    $revenues["amount"] = array();
    $sql = "select i_total as revenue, date(FROM_UNIXTIME(i_date)) as date FROM nexus_invoices WHERE i_status='paid' GROUP BY date(FROM_UNIXTIME(i_date)) ORDER BY i_date DESC LIMIT 0,10";
    $rows = $db->query($sql);
    foreach($rows as $row){
        $revenues["dates"][] = $row['date'];
        $revenues["amount"][] = floatval($row['revenue']);
    }
    //$revenues["amount"] = [1,5,5.5,5.4,5.8,6,8,9,13,12,10,11.5,9,8,5,8,9];
    echo json_encode($revenues);
}

此代码的JSon结果是我期望的结果:

{
    "dates":[
        "2015-06-13","2015-06-12","2015-06-10","2015-06-09","2015-06-07",
        "2015-06-06","2015-06-05","2015-06-04","2015-06-02","2015-05-31"
    ],
    "amount":[8,22,8,8,22,8,8,8,8,8]
}

不幸的是,这不是一个未知的原因。为了进一步调试,我已经取消注释了对$revenues["amount"]进行硬编码的行,并对foreach的第二行进行了注释。然后它工作正常。这个json_encoded回声的结果是:

{
    "dates":[
        "2015-06-13","2015-06-12","2015-06-10","2015-06-09","2015-06-07",
        "2015-06-06","2015-06-05","2015-06-04","2015-06-02","2015-05-31"
    ],
    "amount":[1,5,5.5,5.4,5.8,6,8,9,13,12,10,11.5,9,8,5,8,9]
}

我对数组进行硬编码时的样子:enter image description here

从数据库填充数组时的样子:enter image description here

1 个答案:

答案 0 :(得分:0)

我认为你的问题不在json数组中而是在sparkline插件中。

尝试在显示数据库数据时添加此项:chartRangeMin:5

$(".monthly-sales").sparkline(revenues, {
        type: 'bar',
        barColor: '#ff4e50',
        height: '55px',
        width: '100%',
        barWidth: 8,
        barSpacing: 1,
       chartRangeMin:5 
    });