将数组传递到Google图表上

时间:2019-06-28 17:47:03

标签: javascript php laravel charts google-visualization

我正在尝试使用Google图表绘制甜甜圈图。我正在使用MVC框架,确切地说是laravel。我有一个数组,使用紧凑函数传递给视图。 我确实到处搜索过,但似乎找不到任何指向我的地方,请记住我对javascript还是很陌生。

我已经尝试过:

var data = google.visualization.arrayToDataTable(?= $ frequency?>);

这是我的服务器端php的摘录

 {  
    $memberNames = array_keys($frequency);
    $frequency = array_count_values($members);
    return view('contact.stats', compact('frequency'));

}

这是用于实施图表的google代码

 <script type="text/javascript">
  google.charts.load("current", {packages:["corechart"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var options = {
      title: 'My Daily Activities',
      pieHole: 0.4,
    };

    var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
    chart.draw(data, options);
  }
   </script>

就像我说的,当我返回$ frequency时,它看起来像这样{{female“:74,” others“:2,” na“:63,” male“:59}

我基本上想将$ frequency传递到脚本中的var数据中。

1 个答案:

答案 0 :(得分:0)

php返回一个json对象({}
谷歌图表期望一个数组([]

只需要转换

  var frequency = {"female":74,"others":2,"na":63,"male":59};
  var chartData = [];
  Object.keys(frequency).forEach(function (name) {
    chartData.push([name, frequency[name]]);
  });

在创建google数据表时,
我们需要将true作为第二个参数传递给arrayToDataTable
这表明数组中的第一行是数据,而不是列标题。

  var data = google.visualization.arrayToDataTable(chartData, true);

请参阅以下工作片段...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  //var frequency = <?= json_encode($frequency) ?>
  var frequency = {"female":74,"others":2,"na":63,"male":59};
  var chartData = [];
  Object.keys(frequency).forEach(function (name) {
    chartData.push([name, frequency[name]]);
  });
  var data = google.visualization.arrayToDataTable(chartData, true);

  var options = {
    title: 'My Daily Activities',
    pieHole: 0.4,
  };

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