PHP json_encode进入谷歌饼图

时间:2018-03-27 22:26:42

标签: javascript php

我正在尝试使用PHP数组删除谷歌饼图,但它只显示最后一个值,我该如何解决?

enter image description here

我的JS代码:

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

function drawChart() {
  var a = <?php echo count($supplier); ?>;
  var total = <?php echo json_encode($total); ?>;
  var sup = <?php echo json_encode($namesup); ?>;
  for (var i = 0; i < a; i++) {
    var data = google.visualization.arrayToDataTable([
      ['Supplier Name', 'Performance'],
      [sup[i], total[i]],
    ]);
  }
  var options = {
    title: 'Suppliers Performance'
  };
  var chart = new google.visualization.PieChart(document.getElementById('piechart'));
  chart.draw(data, options);
}

1 个答案:

答案 0 :(得分:-1)

在循环的每次迭代中,您使用新的DataTable覆盖data,并且它始终只包含一个数据行。
用这个替换你的for循环:

// set column names, types
var arr = [{label: "Supplier", type: "String"}, {label: "Performance", type:"number"}];

// add data row to array
for (var i = 0; i < a; i++) {
    arr.push([sup[i], total[i]]);
}

// create DataTable
var data = google.visualization.arrayToDataTable(arr);