Vani Kalapciev
Vani Kalapciev

Reputation: 82

How do I display PHP array in Google Chart

I'd like to diplay my array in google stacked column chart. I generated the array looks like this.

array(n) { ["5pm"]=> int(4) ["6pm"]=> int(0),... } //Monday
array(n) { ["5pm"]=> int(5) ["6pm"]=> int(1),... } //Tuesday
...
array(n) { ["5pm"]=> int(4) ["6pm"]=> int(2),... } //Sunday

The number of entries in array needs to vary (depends on entries in database, but is the same for all days).

The JS from google charts needs to look like this

var data = google.visualization.arrayToDataTable([    
    ['Hours', '5pm', '6pm',...],
    ['Mon', 4, 0],
    ['Tue', 5, 1],
       ...
    ['Sun', 4, 2]
]);

Thanks for the help ;)

Upvotes: 1

Views: 2390

Answers (1)

Suresh
Suresh

Reputation: 5987

Heer is a sample code where I'm getting data from PHP & passing that to JavaScript for plotting the chart. One thing needs to check that all rows should have an equal number of elements.

So, according to your question, all "Time Periods" rows should have an equal number of elements else, it'll not work.

<?php
$chartData = array(
        array('Year', 'Sales', 'Expenses', 'Profit'),
        array('2014', 1000, 400, 200),
        array('2015', 1170, 460, 250),
        array('2016', 660, 1120, 300),
        array('2017', 1030, 540, 350)
    );
$chartDataInJson = json_encode($chartData);
?>

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable(<?php echo $chartDataInJson; ?>);

        var options = {
          chart: {
            title: 'Company Performance',
            subtitle: 'Sales, Expenses, and Profit: 2014-2017',
          }
        };

        var chart = new google.charts.Bar(document.getElementById('columnchart_material'));

        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    </script>
  </head>
  <body>
    <div id="columnchart_material" style="width: 800px; height: 500px;"></div>
  </body>
</html>

Hope it'll clear all of your doubt.

Upvotes: 4

Related Questions