我想在$ country中获得逗号(,)的最后机会。但是我该怎么办?
foreach ($countries as $country) {
$country_id = $country['ID'];
$country = get_the_title().", "; //comma
echo "<pre>";var_dump($country);echo "</pre>";
//string(6) "Taiwan, "
//string(8) "Tanzania, "
//string(14) "United Kingdom, "
echo rtrim($country,", "); //Works not: Taiwan, Tanzania, United Kingdom,
echo substr($country, 0, strlen($country)-1); //Works not: Taiwan, Tanzania, United Kingdom,
echo substr($country, 0, -1); //Works not: Taiwan, Tanzania, United Kingdom,
echo implode(", ", $country); //Works not: Warning: implode(): Invalid arguments passed
echo $country[-1] = PHP_EOL; //Works not: (empty)
echo substr($country, -1); //Works not: (empty)
echo substr(trim($country), 0, -1); //Works not: Taiwan Tanzania United Kingdom
echo str_replace(', ', '', $country); //Works not: TaiwanTanzaniaUnited Kingdom
echo str_replace('', ', ', $country); //Works not: Taiwan, Tanzania, United Kingdom,
}
除了最后一个,我想设置所有的(逗号)。我必须去台湾,坦桑尼亚,英国或台湾坦桑尼亚联合王国。但我更喜欢台湾,坦桑尼亚,英国。 有帮助吗?
答案 0 :(得分:1)
尝试一下
$c=0;
foreach ($countries as $country) {
$country_id = $country['ID'];
$country = get_the_title();
// Add comma only if it is NOT the last $country
if (count($countries)-1 != $c) $country .= ", ";
// display it
echo $country;
$c++;
}
OR
$c='';
foreach ($countries as $country) {
$country_id = $country['ID'];
$c .= get_the_title().", "; //comma
}
// remove comma from last country and display it
echo rtrim($c,", ");