Stephan Botes
Stephan Botes

Reputation: 87

Javascript foreach

I have a javascript for a usage graph , the data for the graph within the javascript is defined as follow:

data: [1,2,3,4,5,6],

I have before the javascript a foreach and a value that im trying to use in this data field as follow :

data: [],

Now if i just do echo "$test"; outside javascript on the page i get the following output 1,2,3,4,5,6, which is correct , if i copy this output and use it directly in the datafield it works BUT when I try to call the $test value within the datafield it does not work. So in short

data: [1,2,3,4,5,6], (WORKS)
data: [<?php echo "$test"; ?>], (does not work even though when doing normal echo outside java it does print 1,2,3,4,5,6

Any help would be appreciated

foreach ($chart->usage->days->day as $day): 
$totals = $day->total;
$datau = Round(("$totals") / (1024 * 1024 * 1024), 2);
$test = "$datau, ";

Upvotes: 0

Views: 261

Answers (1)

kmoney12
kmoney12

Reputation: 4490

Try doing

$test="1,2,3,4,5,6"; //Make sure to remove a trailing comma.
data: [<?php echo $test; ?>]

I don't see any need for the "$test".

Sidenote: You can take out the echo as well. Also, since data is an array, I would store $test as an array as well.

$test=array(1,2,3,4,5,6);
data: [<?= implode(",", $test) ?>]

This looks cleaner in my opinion.

Edit: Based on your foreach, please try:

$test=array();
foreach ($chart->usage->days->day as $day){
$totals = $day->total;
$test[] = round(($totals) / (1024 * 1024 * 1024), 2);
}

data: [<?= implode(",", $test) ?>],

Upvotes: 1

Related Questions