循环,为最后一个条目单独处理(最简单的解决方案) [英] Loop, seperate proces for the last entry (simplest solution)

查看:43
本文介绍了循环,为最后一个条目单独处理(最简单的解决方案)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有的话,我有一个关于循环的问题.目前我的代码如下所示:

I have a question about a loop if I have. Currently my code looks like this:

    $rtitle = "SELECT title FROM table WHERE genre='$category'";
    $ptitles = mysqli_query($connection,$rtitle) or die(mysqli_error($connection));
        while ($title2 = mysqli_fetch_object($ptitles));
        printf('"name": "%s",', $title2->title);

正如您在最后一行中看到的,在标题之后打印了一个逗号.但是,我希望最后一个条目的末尾没有逗号.

As you can see in the last line, after the title a comma is printed. However, I want the last entry to not have comma at the end.

目前我正在考虑为此使用哪些选项.我认为是 if 语句,但是,我不确定如何制定 if 循环来检查最后一个.我考虑过使用计数器,但是我不确定它的效果如何.由于我有几个这样的循环,它们相互依赖,如果可能的话,我想在那里保持 while 循环.

Currently I am thinking about what options to use for that. I think an if statement, however, I'm not sure how I could formulate the if loop to check for the last on. I have considered using a counter, however I am not sure how well that works. Since I have several loops like this, that are dependent on each other, I would want to keep to while loop in there if that is possible.

有没有人对好的方法有任何建议(如果有人有一个很好的例子)?非常感谢!

Does anyone have any suggestion for a good approach (if anyone has an example that would be great)? Many thanks in advance!

推荐答案

可以使用PHP内置函数implode:

You can use the PHP built-in function implode:

string implode ( string $glue , array $pieces )

Join array elements with a glue string. 

php.net/manual/en/function.implode.php

php.net/manual/en/function.implode.php

$names = array();
while ($title2 = mysqli_fetch_object($ptitles)) {
   $names[] = sprintf('"name": "%s"', $title2->title);
}
echo implode(',', $names);

这篇关于循环,为最后一个条目单独处理(最简单的解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆