[英]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, ',');
你可以使用substr
函数(更多信息在这里)
最后一个参数是您想要的子字符串的长度,但您也可以使用负值,这意味着“删除这么多字符”,在您的情况下:1。
在你的情况下:
$followedids = substr($followedids, 0,-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.