php 数组到 google 条形图

php array to google bar chart

好的,我需要帮助从 php 数组创建 google 条形图。 这是我的数组

 array (size=2)
  0 => 
    object(stdClass)[42]
      public 'nombre' => string 'Anillo Princess' (length=15)
      public 'total' => string '5' (length=1)
  1 => 
    object(stdClass)[43]
      public 'nombre' => string 'Shake Sabor Vainilla' (length=20)
      public 'total' => string '1' (length=1)

这是生成图表的代码

 <script type="text/javascript">
      google.load("visualization", "1.1", {packages:["bar"]});
      google.setOnLoadCallback(drawStuff);

      function drawStuff() {
        var data = new google.visualization.arrayToDataTable([
          ['Producto', 'Cantidad'],
          ["Anillo princess", 4],
          ["Shake Sabor Vainilla", 1],
          ["Colageno hidrolisado", 12],
          ["Proteina lifeone", 10],
          ['otros', 3]
        ]);

        var options = {
          title: 'Productos mas vendidos',
          width: 900,
          legend: { position: 'none' },
          chart: { subtitle: 'Cantidad vendidas' },
          axes: {
            x: {
              0: { side: 'top', label: 'Productos'} // Top x-axis.
            }
          },
          bar: { groupWidth: "90%" }
        };

        var chart = new google.charts.Bar(document.getElementById('top_x_div'));
        // Convert the Classic options to Material options.
        chart.draw(data, google.charts.Bar.convertOptions(options));
      };
    </script>

如何将变量传递给脚本以使用数组中的值生成图表。

感谢大家的帮助!

干杯。

尝试一下:

<?
    //original array
    $arr = [
        ['nombre' => 'Anillo Princess', 'total' => '5'],
        ['nombre' => 'Shake Sabor Vainilla', 'total' => '1']
    ];

    //loop and build output array
    $output = [["Producto", "Cantidad"]];
    foreach($arr as $row) {
        $output[] = [$row['nombre'], $row['total']];
    }

    //echo the result
    echo json_encode($output);
?>

如果您只想像这样直接在代码中回显数组:

var data = new google.visualization.arrayToDataTable(<?=json_encode($output)?>);

但您可以使用 ajax 请求加载数据