带有JSON数据的Morris图表

时间:2016-06-16 07:05:21

标签: php json morris.js

我有这个代码用于将db查询(sql server)输出到我本地目录上的.json文件。

    $connectionInfo = array("");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);
    if( $conn )
        {
      }else
        { echo "Connection could not be established.\n";
                die( print_r( sqlsrv_errors(), true));
      }

   $sql="";
   $query = sqlsrv_query( $conn, $sql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));

    if( $query === false ) {
        echo "Error in executing query.</br>";
            die( print_r( sqlsrv_errors(), true));
    }

    $json = array();

    do {
        while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {
            $json[] = $row;
        }
    } while ( sqlsrv_next_result($query) );

        file_put_contents('data.json', json_encode($json));

这部分工作正常,它以这种格式输出json数据。

[{"month":1,"a":43,"b":10},{"month":2,"a":43,"b":87},{"month":3,"a":52,"b":11},{"month":4,"a":66,"b":25},{"month":5,"a":30,"b":11},{"month":6,"a":29,"b":10},{"month":7,"a":32,"b":41},{"month":8,"a":27,"b":36},{"month":9,"a":36,"b":32},{"month":10,"a":57,"b":57},{"month":11,"a":32,"b":20},{"month":12,"a":53,"b":65}]

在另一页上,我正在使用JSON数据初始化这个Morris-area-chart,如下所示:

首先我正在读取JSON文件并循环遍历数组。

$final = json_decode(file_get_contents('data.json'));
    $new_final = array();

    foreach($final as $value) {
        foreach($value as $sub_value) {
            $new_final[] = $sub_value;
        }
    }

        echo json_encode($new_final);
        exit;
    }

第二次使用Ajax在同一页面上使用(document.url)初始化morris图表:

$(document).ready(function(){

    $.ajax({
        url: document.URL,
        dataType: 'JSON',
        type: 'POST',
        data: {get_values: true},
        success: function(response) {

         Morris.Area({
                element: 'area-chart',
                data: response,
                xkey: 'month',
                ykeys: ['a','b'],
                labels: ['Month', 'Total']
            });
        }
    });

});

它没有输出图表。我确实发现当你操纵.JSON文件并添加额外的'[]'时,它正常工作并按预期输出,如下所示:

[[{"month":1,"a":43,"b":10},{"month":2,"a":43,"b":87},{"month":3,"a":52,"b":11},{"month":4,"a":66,"b":25},{"month":5,"a":30,"b":11},{"month":6,"a":29,"b":10},{"month":7,"a":32,"b":41},{"month":8,"a":27,"b":36},{"month":9,"a":36,"b":32},{"month":10,"a":57,"b":57},{"month":11,"a":32,"b":20},{"month":12,"a":53,"b":65}]]

有人可以告诉我我在这里监督什么吗?看起来我需要第二个阵列,但我不确定..提前谢谢。

1 个答案:

答案 0 :(得分:0)

我明白了,

$final = json_decode(file_get_contents('data.json'));
    $new_final = array();

    foreach($final as $value) {
        foreach($value as $sub_value) {
            $new_final[] = $sub_value;
        }
    }

        echo json_encode($new_final);
        exit;
    }

应该是

$final = json_decode(file_get_contents('../php/data.json'));
    $new_final = array($final);

    foreach($final as $value) {

    }
        echo json_encode($final);
        exit;
    }