2

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks zedd, how would i do it with an ajax request?
do you have jQuery or is it vanilla javascript?
then there is an example here (use the php code above as the page that gets called): developers.google.com/chart/interactive/docs/php_example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.