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
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.
You can use json_encode, I think it will give you the kind of output you want.
Like this :
Then pass $output to JS and use it like this :