mtzStrada
mtzStrada

Reputation: 63

php array to google bar chart

Ok guys i need help creating a google bar chart from a php array. this is my array

 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)

and this is the code for generating the chart

 <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>

how do i pass the variable to the script to generate the chart with the values in the array.

Thans for the help guys!

cheers.

Upvotes: 2

Views: 1597

Answers (1)

BobbyTables
BobbyTables

Reputation: 4685

Heres an attempt:

<?
    //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);
?>

this is if you just want to echo the array straigth in your code like so:

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

but you could load the data with an ajax request

Upvotes: 1

Related Questions