简体   繁体   English

如何从While循环中的最后一个字符串中删除最后一个字符?

[英]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.我正在尝试在 Google Charts 脚本中插入一个 PHP 循环,其中包含来自我的 mysql 数据库的数据。

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.我已经尝试过 function LTRIM,但它会从循环中的每个字符串中删除它,而不仅仅是最后一个。

What would be the best solution to fix this problem?解决此问题的最佳解决方案是什么?

First off, don't use count() in a loop.首先,不要在循环中使用 count() 。 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.就个人而言,我会在这里使用 for() 循环。

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 = 0; $i < $count; $i++)
{
    echo ....
    if $i < $count
    {
        echo ", ";
    }
}

You can use json_encode, I think it will give you the kind of output you want.你可以使用json_encode,我想它会给你你想要的那种output。

Like this:像这样:

$arr = array();

foreach ( $result as $res ) {

    $dato = $res->dato;
    $vaegt = $res->vaegt;

    $arr[$dato] = $vaegt; 

}

$output = json_encode($arr);

echo $output;

This is going to output:这将转到 output:

{"dato1":"vaegt1","dato2":"vaegt2", etc...} {“dato1”:“vaegt1”,“dato2”:“vaegt2”,等等...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM