Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array in Javascript?

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.

like image 422
Chris Avatar asked Jul 12 '26 10:07

Chris


1 Answers

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;
like image 81
MrCode Avatar answered Jul 15 '26 00:07

MrCode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!