我有一个代码php
foreach ($cities as $city) {
echo substr($city->name . ", ", 0, -2);
}
结果是:a,b,c,d,e,
如何删除foreach()中的“,”
确切地说:a,b,c,d,e
答案 0 :(得分:8)
答案 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);
答案 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)
答案 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;