March 5, 2012

How to echo a php array for dynamic javascript

Question by ToddN

I am using Google Analytics API to pull Total Visits and put into Googles Javascript to display in a bar graph. I am having issues trying to put an array to the variables. When I do a print_r it spits out everything just fine but I need it to spit out everything just as it is. This is what I got so far:

//I connect to my own SQL database for $num

//Connect to Google Analytics
$mystart = '2012-02-28';

$i=0;
while ($i < $num) {

        $ga->requestReportData(ga_profile_id,array('source'),array('visits', 'visitBounceRate'),'-visits', $filter, $mystart, $mystart);

//adds +1 day to date 
$mystart = date('Y-m-d', strtotime("+1 day", strtotime($mystart)));

$totalvisits = $ga->getVisits();

//These are my arrays  
$adddate[] = "data.addColumn('number', '" . $mystart . "');";
$addvisits[] = "$totalvisits,";
        }

This is what I am trying to achieve through the use of echos:

<script type="text/javascript">
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Date');
        // This is where I want to put something like <? echo $adddate ?> but of course doesn't work
        data.addColumn('number', '2012-02-28');
        data.addColumn('number', '2012-02-29');
        data.addColumn('number', '2012-03-01');
        data.addColumn('number', '2012-03-02');
        data.addColumn('number', '2012-03-03');
        data.addRows([
        // This is where I want to put something like <? echo $addvisits ?> but of course doesn't work
          ['Feb. 28 to March 3', 100, 105, 91, 80, 150]
        ]);
</script>

Answer by Ynhockey

If you are asking how to output the array in the way you want, then use something like:

echo implode("rn", $adddate);

See implodeDocs.

Answer by Starx

Of course, it will work, you cannot echo an array. The easiest way is to implode them

Use these codes, where you are echoing them right now

echo implode("",$adddate);
echo implode("",$addvisits);
// User rn to implode if you need to add linebreaks

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!