Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda