简体   繁体   English

如何在除字符串中的最后一项之外的所有内容中添加逗号

[英]How to add commas to all except last item in string

How do i add a comma after each row except for the last row. 如何在除最后一行之外的每一行之后添加逗号。

while ($row = mysqli_fetch_array($result))
{
echo $row['categoryID']." ";
}

Currently displaying Action Adventure Drama I want it to display like this Action, Adventure, Drama 目前显示动作冒险剧我希望它显示像这个动作,冒险,戏剧

If i just echo the comma it will display like Action, Adventure, Drama, 如果我只是回显逗号,它将显示为动作,冒险,戏剧,

You need to simply take an array of categories. 您只需要采用一系列类别。

And convert it into a string by implode() . 并通过implode()将其转换为字符串。

This is the simplest solution we can have. 这是我们可以拥有的最简单的解决方案。

<?php
$categories = array();
while ($row = mysqli_fetch_array($result)) {
 $categories[] = $row['categoryID'];
}
echo implode(', ' , $categories);
?>

If you use string function, you need to append new category ids every time in the loop along with comma. 如果使用字符串函数,则每次在循环中都需要在逗号后附加新的类别ID。

And then remove comma from right part of string using rtrim() . 然后使用rtrim()从字符串的右侧部分删除逗号。

Instead of this implode() works in one go. 而不是这个implode()一次性工作。

TRY rtrim() to remove last comma from string TRY rtrim()从字符串中删除最后一个逗号

Using string :- use rtrim() to cut last comma from string 使用字符串 : - 使用rtrim()从字符串中删除最后一个逗号

$str='';
while ($row = mysqli_fetch_array($result)) {
  $str .= $row['categoryID'].", ";
}
$str = rtrim($str,',');

Using array :- use implode() to convert array in string with glue(comma) 使用数组 : - 使用implode()用胶水(逗号)转换字符串中的数组

$str = array();
while ($row = mysqli_fetch_array($result)) {
  $str[] = $row['categoryID'].", ";
}
$newstr = implode(', ' , $str);

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

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