skip to Main Content

I am trying to insert a PHP loop with data from my mysql database inside a Google Charts script.

My result from the database looks like this:

$result = $wpdb->get_results(
    "Query"); 

The loop that I am trying to make is supposed to look like this

['$result',  $result],

And this is what I have come up with so far

$count = 0;
while ($count < count($result)) {
    echo "['" . $result[$count]->dato . "', " . $result[$count]->vaegt . "].<br>";
    $count++;
    }

Which create the string that I am looking for. The problem is that I need to remove the comma from the last string in the loop.

I have tried the function LTRIM, but it removes it from every string in the loop, not just the last.

What would be the best solution to fix this problem?

2

Answers


  1. First off, don’t use count() for a fixed result in a loop. It may look convenient, but it’s slower as it performs the operation over and over on each iteration. Assign the count result to a variable first. And personally, I would use a for() loop here.

    Secondly, you need to use a condition inside the loop. Rather than trying to remove the last comma just run a check on the iteration count, if it’s not last then add a comma.

    $count = count($result);
    for($i = 1; $i <= $count; $i++)
    {
        echo "....";
        if($i < $count)
        {
            echo ", ";
        }
    }
    
    Login or Signup to reply.
  2. You can use json_encode, I think it will give you the kind of output you want.

    Like this :

    $arr = array();
    
    foreach ( $result as $res ) {
    
        $dato = $res->dato;
        $vaegt = $res->vaegt;
    
        $arr[$dato] = $vaegt; 
    
    }
    
    $output = json_encode($arr);
    

    Then pass $output to JS and use it like this :

    var data = new google.visualization.DataTable("your JSON variable");
    
    var options = {
     title:your option,
     legend:your option,
     chartArea:your option
    };
    
    var chart = new google.visualization.LineChart(document.getElementById("the ID of the HTML element in which you want to output the result"));
    
    chart.draw(data, options);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search