Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
How to remove the last character from last string in a While loop?

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?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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 ", ";
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda