如何删除foreach()中的“,”?

时间:2011-12-28 08:25:18

标签: php

我有一个代码php

foreach ($cities as $city) {
     echo substr($city->name . ", ", 0, -2);
}
  

结果是:a,b,c,d,e,

如何删除foreach()中的“,”

  

确切地说:a,b,c,d,e

8 个答案:

答案 0 :(得分:8)

使用implode函数可以用更少的代码实现相同的效果。

$comma_separated = implode(',', $cities);

应该准确地给你你想要的东西。

答案 1 :(得分:1)

$str = '';
foreach ($cities as $city){
    $str .= "$city, ";
}
$str = rtrim($str, " ,");

答案 2 :(得分:1)

在此上下文中,如果没有其他标记,则无法删除最后一个逗号。

您还有两个选择:

<强> 1。使用标准循环:

for ($i=0; $i < count($cities)-1; $i++) {
    echo $cities[$i]->name . ", ";
}
echo $cities(count($cities)-1)->name;

<强> 2。在foreach中创建一个结果字符串,删除最后一个字符,然后打印它。

答案 3 :(得分:1)

只需: -

<德尔> echo implode(',', $cites);

这将为您提供所需的输出。
我刚从你的代码中注意到$cities是一个对象而不是一个数组,对不起: -

foreach($cities as $city){
    $cityNames[] = $city->name;
}
echo implode(',', $cityNames);

http://www.php.net/implode

答案 4 :(得分:0)

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

答案 5 :(得分:0)

将其改为:

$first = TRUE;

foreach ( $cities as $city )
{
    if ( !$first )
    {
        echo( "," );
    }

    $first = FALSE;
    echo( $city->name );
}

答案 6 :(得分:0)

foreach()

之后使用rtrim
$city->name = rtrim($city->name,',');

答案 7 :(得分:0)

方法1:

$index = 0;
    foreach ($cities as $city) {
    $index++;
    echo $city->name . ($index == count($cities)?"":",");

    }

方法2:

$str = "";
    foreach ($cities as $city) {
    $str .=  $city->name . ",";    
    }
$str = substr_replace($str ,"",-1);
echo $str;