Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从While循环中的最后一个值中删除逗号_Php - Fatal编程技术网

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

Php 从While循环中的最后一个值中删除逗号,php,Php,我的主要目的是从数组的最后一个值中删除逗号“” $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

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

$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);
}}
如果I
echo$followerdids
结果如下,并带有逗号:

五,七,八,

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

您可以使用
substr
-函数(更多信息)

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

就你而言:

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

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

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

你问题的解决办法很简单。有一个名为()的函数,用于删除右侧的所有字符

$followedids = rtrim($followedids, ',');
还有一个()函数,它在两侧执行相同的操作,还有()函数在左侧执行相同的操作。

您只需要:

$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注入

总是很高兴看到同一个问题有多种可能性!:)谢谢,我知道答案了!但是您使用的变量不正确。它必须是
$arraystr=rtrim($arraystr,,')不是真的,不需要两行分解和内爆数组,因此变量是正确的,应该在while循环之后执行。您只需要将字符串值(rtrim)修剪到右边,我看不出输出是如何生成的。我想说下面的答案回答了…我也花了一段时间,但最后,他自己给$followerids添加了一个逗号^^^对我之前评论的解释:op没有用
保留变量内容,因此,它应该覆盖
$arraystr
,这意味着基本上变量
$ids['acc_id']
已经带来了由
分隔的值,
,OP在使用
$ids['acc_id']时增加了问题。编辑:看。我喜欢这个答案胜过其他答案,虽然其他答案都很好并且达到了效果,但它们看起来更像是绷带,因为这是最好的答案fix@Dale是的,这可能是唯一一个与我在问题评论中提到的答案相同的答案。这个[]意味着什么?它意味着,将新元素添加到$followedIds数组
$followedIds=[]
$followedIds=array()
相同,但它是在我得到答案后引入的!但是您使用的变量不正确。它必须是
$arraystr=rtrim($arraystr,,')