3

I want to print a statistical graph through my PHP file when it's function is called. I use Google Charts API for the GUI and print of the actual graphs.

Here is a snippet from code I got from Google API (javascript):

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

What I want to do is to replace the above values with PHP variables (probably a 2D-array) but I have not managed to get it to work. It either gives me a PHP error, or prints nothing, depending on what I try.

This is what I tried:

var data = google.visualization.arrayToDataTable(
    $array[0][0],$array[0][1],$array[0][2]],
    $array[1][0],$array[1][1],$array[1][2]],
    $array[2][0],$array[2][1],$array[2][2]],
    $array[3][0],$array[3][1],$array[3][2]],
    $array[4][0],$array[4][1],$array[4][2]]
);

and the array I made:

$array = array(array('Year', 'Sales', 'Expenses'), array('2004', 1000, 400), ... );

Ideas anyone? :) Thanks.

5
  • what are the errors? have you tried print_r on $array, $array[0] and $array[0][1]? Commented Apr 24, 2014 at 16:44
  • You could try to convert to JSON - probably then it will be much easier to work with from both sides. Commented Apr 24, 2014 at 16:45
  • You are missing an opening square bracket in your "tried" section for each line. But really you should just be able to call json_encode on the array. Commented Apr 24, 2014 at 16:46
  • so just $array = json_encode($array); or? Commented Apr 24, 2014 at 16:49
  • and yes, that bracket was an accidental leftover from my last failed solution. :P Commented Apr 24, 2014 at 16:50

1 Answer 1

4

Your PHP array format matches the structure required for the chart, so you can simply JSON encode it:

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

This works because JSON is valid plain old JavaScript when assigned to a variable or passed as a function argument.

Whenever you output PHP variables into the page, you need to use the PHP tags and echo or similar.


If the JavaScript is in a PHP string that you echo, you can just concatenate the JSON into it , for example

$js = '
    <script>
    var data = google.visualization.arrayToDataTable(
    ' . json_encode($array) . '
    );
    </script>
';
echo $js;
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, this did not work for me. I get no error, but nothing is printed on screen.
Is the JavaScript in a PHP string? or do you close the PHP tag to output the JS?

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.