We help IT Professionals succeed at work.

Google Charts line graph from PHP arrays

msibley
msibley used Ask the Experts™
on
I have a PHP script that processes data from a MySQL database. It basically is a series of amplitude values for a range of frequencies. The output winds up in 2 arrays, one holds the frequency (1, 1.5, 2, 2.5 ... 30) and the other holds the amplitude values (for example 2.5, 1.6, 9.5, etc.). What I'd like to do is output a simple line graph using these arrays, with the x axis being the frequency and the y axis the amplitude. I'm having difficulty figuring out how to input the arrays directly into the Google Charts code.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fractional CTO
Distinguished Expert 2018
Commented:
Each type of specific Google Chart usually provides many related examples.

Try this debug sequence.

1) Best to just take one of the examples, to verify you have Google Charts working.

2) Then just substitute in your data, via hardcoding data.

3) Then move on to using data pulled from a database.

Remember: Always debug complex code incrementally, in steps.

Author

Commented:
I cannot seem to find an example of coding with an array in php. I’ve found examples using hard-coded arrays for the data. I need it to work dynamically based on queries. For clarification, I’m not looking for examples of using a sql query to create the array. I want to pass arrays or a combined array.

Currently, as a workaround, I’m trying to use an example that imports a json data file, by outputting the arrays in a format similar to the example I have, and then using that file as the data source. Not very eloquent and it will require me to link to a new page to read the data in the <head> section, rather than handling it all in one fell swoop with one script.

Hopefully, thus makes sense. I’m just a self-taught junky code hack.
NorieAnalyst Assistant

Commented:
How are you creating/populating the arrays?

Are you manipulating/processing the data returned from your query in some way?
Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013
Commented:
I cannot seem to find an example of coding with an array in php. I’ve found examples using hard-coded arrays for the data. I need it to work dynamically...

What David is suggesting is really the best option and I do this myself and especially with charts because they can be hard to wrap your head around them at first and there may be other points of failure that has nothing to do with your data.  Keep in mind that the charts in this case are javascript and that means rendered on the client. All that matters is the rendered code. All you need your php for is to render the data.  

Looking at the example https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/gallery/linechart.html
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>

Open in new window


First get the example to run on your site. Once it is running, you know everything is in place. Next step is to replace the example data with your own

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

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

        var options = {
          title: 'Company Performance',
          curveType: 'function',
          legend: { position: 'bottom' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 900px; height: 500px"></div>
  </body>
</html>

Open in new window


Now your only job is to generate $data

There is another example that may be easier to follow https://developers-dot-devsite-v2-prod.appspot.com/chart/interactive/docs/php_example

In that example they are using ajax and the ajax page is simply
<?php 

// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.

$string = file_get_contents("sampleData.json");
echo $string;

// Instead you can query your database and parse into JSON etc etc

?>

Open in new window

where the sampleData.json file is
{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}

Open in new window


In the php file just above, you can replace the two lines outputing $string to calling your database and outputting your json data. You don't have to have an actual json file.

Author

Commented:
Thanks to all who contributed. I experimented with writing a script to output data to a text file, then reading it in to the chart. This required me to link to another page, but it works. It isn't the solution I was looking for of doing it all in one fell swoop.
David FavorFractional CTO
Distinguished Expert 2018

Commented:
You're welcome!
Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
I think you can refine what you're doing into one Ajax request. that is what my example is trying to show.

you have an external page that accepts data input processes the data and outputs data for the chart.then your original page made the Ajax request is able to extract that and place it on the page where your chart is.

I think that maybe more confusing the right than it actually is. hopefully if you reread my example it'll make more sense.
Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
if you post what you're doing perhaps we can help refine here