繁体   English   中英

从 While 循环中的最后一个值中删除逗号

[英]Remove comma From the last value in a While loop

我的主要动机是从数组的最后一个值中删除逗号“,”。

$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
     if (mysqli_num_rows($Followingcount) > 0) {
    while ($ids = mysqli_fetch_assoc($Followingcount)) {
     $followedids = $ids['acc_id'].',';
     $array = array($followedids);
     $arraystr = implode("','",$array);
}}

如果我echo $followerdids结果是这样的,逗号如下:

5, 7, 8,

为了删除最后一个值处的逗号,我尝试将这些值放在一个数组中,然后我将其内爆。 当我echo $arraystr它仍然包含最后一个值的逗号。

您只需要:

$followedIds = [];

$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
     $followedIds[] = $ids['acc_id'];
}

echo implode(',', $followedIds);

...并注意 SQL 注入

您可以使用 rtrim 删除 while 循环后的最后一个逗号。

$followedids = rtrim($followedids, ',');

您的问题的解决方案非常简单。 有一个函数叫rtrim (),就是去掉右边的所有字符。

$followedids = rtrim($followedids, ',');

还有一个trim ()函数,它对两边做同样的事情,而ltrim ()对左边做同样的事情。

你可以使用substr函数(更多信息在这里

最后一个参数是您想要的子字符串的长度,但您也可以使用负值,这意味着“删除这么多字符”,在您的情况下:1。

在你的情况下:

$followedids = substr($followedids, 0,-1);

暂无
暂无

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

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