koolaid_Mixin_Jones
koolaid_Mixin_Jones

Reputation: 76

Javascript FOR loop inside of an array

I have been avoiding javascript for a while now but need to use it for a google chart I am using. My original code looks like this...

echo "function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Machines Total'  ],

      [ '$Day[6]', $Hour_Tot[7].$Min_Tot[7] ], 
      [ '$Day[5]', $Hour_Tot[6].$Min_Tot[6] ], 
      [ '$Day[4]', $Hour_Tot[5].$Min_Tot[5] ],
      [ '$Day[3]', $Hour_Tot[4].$Min_Tot[4] ],
      [ '$Day[2]', $Hour_Tot[3].$Min_Tot[3] ],
      [ '$Day[1]', $Hour_Tot[2].$Min_Tot[2] ],
      [ '$Day[0]', $Hour_Tot[1].$Min_Tot[1] ]

      ]);";

This code works just fine, and has been tested. What I am trying to do now is have the chart become more dynamic so a user can enter in a number and the chart can ouput the data for the number of days. So I need to add in a for loop. This is what I got so far.

echo "function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Machine L1'  ],
      for (count = 1, DayNumber = 0; count == 7; ++count, ++DayNumber ) 
  document.write([ '$Day[DayNumber]', $Hour_Tot[count].$Min_Tot[count]],);
       ]);";

This code does not work. I do not understand how to use the document.write to output the 7 lines I need to replicate the above code.

Upvotes: 0

Views: 160

Answers (1)

Bruno Alves de Faria
Bruno Alves de Faria

Reputation: 26

This code is not going to work because you're putting a for loop inside an array declaration. You should do the following...

echo "function drawChart() {
var data = google.visualization.arrayToDataTable([
  ['Date', 'Machine L1'  ],";
for ($count = 1, $DayNumber = 0; $count <= 7; ++$count, ++$DayNumber ) {
  echo "  [ '$Day[$DayNumber]', $Hour_Tot[$count].$Min_Tot[$count]],";
}
echo "]);";

Or you can also handle that using javascript, it should looks like:

echo "var arr = [['Date', 'Machine L1']];
  for(var i=1;i<=7;i++) {
    arr.push([{$Day}[i-1], {$Hour_Tot}[i].toString()+{$Min_Tot}[i].toString()]);
  }
  var data = google.visualization.arrayToDataTable(arr);
";

Upvotes: 1

Related Questions