如何用这个动态数组填充谷歌图表?

时间:2017-05-19 13:53:41

标签: javascript php arrays json google-visualization

我想学习如何从基于SQL查询的数组填充谷歌图表。该数组可以包含不同数量的结果,具体取决于它运行的日期。我用手动输入数据创建了图表,所以我知道它有效,但当我尝试从数组中读取数据时,我不会成功。

这是数组

x % 2 == 1

这是我的图表:

Array

(

    [0] => Array
        (
            [0] => Mobillyftar
            [PRODUCT_GROUP] => Mobillyftar
            [1] => 20
            [WEEK] => 20
            [2] => 54
            [QTY] => 54
        )

    [1] => Array
        (
            [0] => Selar
            [PRODUCT_GROUP] => Selar
            [1] => 20
            [WEEK] => 20
            [2] => 808
            [QTY] => 808
        )

    [2] => Array
        (
            [0] => Taklyftar
            [PRODUCT_GROUP] => Taklyftar
            [1] => 20
            [WEEK] => 20
            [2] => 6
            [QTY] => 6
        )

    [3] => Array
        (
            [0] => Tillb & res
            [PRODUCT_GROUP] => Tillb & res
            [1] => 20
            [WEEK] => 20
            [2] => 1159
            [QTY] => 1159
        )

)

1 个答案:

答案 0 :(得分:0)

建议在php中构建数组,类似于以下内容......

$table = array();

$table['cols'] = array();
$table['cols'][] = array('label' => 'WEEK', 'type' => 'string');
$table['cols'][] = array('label' => 'Mobillyftar', 'type' => 'number');
$table['cols'][] = array('label' => 'Selar', 'type' => 'number');
$table['cols'][] = array('label' => 'Taklyftar', 'type' => 'number');
$table['cols'][] = array('label' => 'Tillb', 'type' => 'number');

$row = array();
$row[] = array('v' => '20');
$row[] = array('v' => 54);
$row[] = array('v' => 808);
$row[] = array('v' => 6);
$row[] = array('v' => 1159);
$table['rows'] = array('c' => $row);

应该导致以下json ...

{"cols":[
  {"label":"WEEK","type":"string"},
  {"label":"Mobillyftar","type":"number"},
  {"label":"Selar","type":"number"},
  {"label":"Taklyftar","type":"number"},
  {"label":"Tillb","type":"number"}
],
"rows":[
  {"c":[{"v":"20"},{"v":54},{"v":808},{"v":6},{"v":1159}]}
]}

然后可以直接用于创建数据表...

var data = new google.visualization.DataTable(jsonData);

请参阅以下工作代码段...

google.charts.load('current', {packages:['bar']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var jsonData = {
    "cols":[
      {"label":"WEEK","type":"string"},
      {"label":"Mobillyftar","type":"number"},
      {"label":"Selar","type":"number"},
      {"label":"Taklyftar","type":"number"},
      {"label":"Tillb","type":"number"}
    ],
    "rows":[
      {"c":[{"v":"20"},{"v":54},{"v":808},{"v":6},{"v":1159}]}
    ]
  };

  var data = new google.visualization.DataTable(jsonData);

  var chart = new google.charts.Bar(document.getElementById('chart_div'));
  chart.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>