php 从 foreach 循环中去除最后一个逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4705814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:04:05  来源:igfitidea点击:

Stripping last comma from a foreach loop

php

提问by Cecil

Im using a foreach loop to echo out some values from my database, i need to strip the last comma from the last loop if that makes sense.

我使用 foreach 循环从我的数据库中回显一些值,如果有意义的话,我需要从最后一个循环中去除最后一个逗号。

My loop is just simple, as below

我的循环很简单,如下

foreach($results as $result){
  echo $result->name.',';
}

Which echos out

哪个回响

result,result,result,result,

I just need to kill that pesky last comma.

我只需要杀死那个讨厌的最后一个逗号。

Any help would be great :)

任何帮助都会很棒:)

Cheers

干杯

采纳答案by shamittomar

First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:

首先使用输出缓冲获取所有输出。然后,修剪逗号并显示它。所以,这样做:

ob_start();
foreach($results as $result)
{
   echo $result->name.',';
}
$output = ob_get_clean();

echo rtrim($output, ',');

The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

如果内部循环非常大(并且 OP 在这里发布只是为了简洁),则输出缓冲方法会有所帮助,然后在不更改循环内部的情况下使用 OB 会更容易。

回答by LeleDumbo

Better:

更好的:

$resultstr = array();
foreach ($results as $result) {
  $resultstr[] = $result->name;
}
echo implode(",",$resultstr);

回答by Glavi?

1. Concat to string but add |before

1.连接到字符串但|之前添加

$s = '';
foreach ($results as $result) { 
    if ($s) $s .= '|';
    $s .= $result->name; 
}
echo $s;

2. Echo |only if not last item

2.|只有当不是最后一项时才回声

$s = '';
$n = count($results);
foreach ($results as $i => $result) { 
    $s .= $result->name;
    if (($i+1) != $n) $s .= '|';
}
echo $s;

3. Load to array and then implode

3.加载到数组然后内爆

$s = array();
foreach ($results as $result) { 
    $s[] = $result->name;
}
echo implode('|', $s);

4. Concat to string then cut last |(or rtrimit)

4.连接到字符串然后最后切|(或rtrim它)

$s = '';
foreach ($results as $result) { 
    $s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');

5. Concat string using array_map()

5. Concat 字符串使用 array_map()

echo implode('|', array_map(function($result) { return $result->name; }, $results));

回答by Mike

$result_names = '';
foreach($results as $result){
    $result_names .= $result->name.',';
}
echo rtrim($result_names, ',');

回答by jrgresh92

I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.

我最近在这个类似的问题上遇到了同样的问题。我通过使用增量变量 $i 来修复它,将其初始化为 0,然后让它在 foreach 循环内递增。如果 $i 计数器小于数组/变量的 sizeof() 运算符,则在该循环中放置一个 if、else 和包含逗号的 echo 语句。

I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.

我不知道这本身是否会解决您的问题,但它对我的问题有所帮助。我意识到这个问题已有多年历史,但希望这会对其他人有所帮助。我对 PHP 还很陌生,所以我不太明白在我之前给出的很多答案,尽管它们很有见地,尤其是内爆的。

$i=0;
foreach ($results as $result) {
    $i++;
    if(sizeof($results) > $i) {
        echo $result . ", ";
    } else {
        echo $result;
    }
}

回答by Adam Ellis

$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
  $comma = ($i<$arraySize) ? ", " : "";
  echo $results[$i]->name.$comma;
}

回答by Sohil Shingala

$string = "";
while ($row = mysql_fetch_array($result)) {
  $string .= $name . ', ';
}
echo substr($string, 0, strlen($string) - 2);

回答by Alex Russell

Not as pretty, but also works:

不那么漂亮,但也有效:

$first=true;
foreach($results as $result){
    if(!$first) { echo ', '; }
    $first=false;
    echo $result->name;
}

回答by shvmsngh99

<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
    $str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
    if($len > $i)
    {
        $str .= ',';
        $i = $i+1;
    }
}
echo $str;
?>

回答by Amir Fo

Pretty easy with end($array)here:

end($array)在这里很容易:

foreach($results as $result){
  echo $result->name . (end($results) ? '' : ',');
}

referencehere.

参考这里。



Another smart way is:

另一个聪明的方法是:

foreach($results as $result){
  echo ($passed ? ',' : '') . $result->name;
  $passed = true;
}

In this case at first loop $passedis NULLand ,doesn't print.

在这种情况下,第一个循环$passedNULL并且,不打印。

回答by heady12

<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
    echo $result->name;
    if ( $i < $count ) echo ", ";                               
    ++$i;
}
?>