Problems with PHP's array_shift in an HTML script

0

I have a problem that I can not solve and I hope you can help me:

I am working on Wordpress with PHP and HTML to extract data from a server with MYSQL and then to show this data on screen in a graphic thanks to Google charts.

Both taking data and storing it in an array works. Within php I make a short loop of 10 laps to show me the first 10 values of the array:

for ($i=0; $i<10; $i++){
   foreach ($elemento = array_shift($rIN) as $v1){
      echo "$v1--";
   }
}

This code works perfectly and shows me the first 10 values of the array as I need.

Now yes, the problem is when I need to do the same thing in an HTML script.

for(i=0,i<10,i++){
         data.addRow([i,<?php foreach ($elemento = array_shift($rIN) as $v1){echo "$v1";}?>]);
         }

In this case, google charts only graph me in all the values of x (0,1,2,3 .., 10) exactly the first value of the array only, that is to say, graph only a horizontal straight line.

If within the loop I add another data.addRow line exactly like the previous one, I graph the first and the second value in this way:

In summary, every time you start the loop again it is as if you had never applied the array_shift and the array was never modified.

In google charts (JS with PHP):

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawHour);
google.charts.setOnLoadCallback(drawDay);
function drawHour() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Hora');
  data.addColumn('number', 'IN');
  data.addColumn('number', 'OUT');
  for (i=0; i<1; i++){
    data.addRow([i,<'?php foreach ($elemento = array_pop($rIN) as $v1){echo "$v1";}?>,<'?php foreach ($out = array_pop($rOUT) as $v2){echo "$v2";}?>]);
    
asked by Pablo Toledo 15.12.2017 в 16:44
source

1 answer

0

The problem lies in the order of execution of each language.

  • PHP is compiled on the server ( runs first ) and the result is returned to the browser ('agent making the solution').

  • The browser takes that result returned by the server and executes JS (among other things).

That is to say that, on each round of for of JS , the values printed by PHP are already in the document, and they will always be the same.

Solution:

You could generate the code JS with PHP .

Example:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Hora');
data.addColumn('number', 'IN');
data.addColumn('number', 'OUT');
<?php
for ($i=0, $i<1, $i++) {

    echo "data.addRow([$i,";
    foreach ($elemento = array_shift($rIN) as $v1) { echo "$v1"; }
    echo ",";
    foreach ($out = array_pop($rOUT) as $v2){echo "$v2";}
    echo "]);";
} ?>
    
answered by 15.12.2017 в 17:53