<?php
one = "A";
$two = "B";
$three = "C";
$four = "D";
$message = "";
$hello = array();
$hello['one'] = $one;
$hello['two'] = $two;
$hello['three'] = $three;
$hello['four'] = $four;
foreach ($hello as $value){
if (empty($value)){
$message .= $value;
} else
$message .= $value.",";
}
echo $message;
?>
上面的代码给出的输出为:A,B,C,D,请给我一种方法来删除最后一个逗号,即使我删除了任何其他值。谢谢
使用rtrim()
并将,
作为需要修剪的字符之一。
$message = rtrim($message, ',');
echo $message;
只是不要添加您不想使用的逗号。可以用implode()
很好地完成
<?php
$one = "A";
$two = "B";
$three = "C";
$four = "D";
$message = "";
$hello = array();
$hello['one'] = $one;
$hello['two'] = $two;
$hello['three'] = $three;
$hello['four'] = $four;
$message = implode(',', $hello);
echo $message;
implode()
连接给定数组的所有值,并将第一个参数(称为"glue")放在所有值之间。
请查看 http://php.net/manual/en/function.implode.php 以获取进一步的解释和示例。
如果数据中有空值,则可能需要执行一些预处理,以仅implode()
具有实际内容的部件:
$output = array();
foreach ($hello as $value){
if (!empty($value)){
$output[] = $value;
}
}
$message = implode(',', $output);
echo $message;
您可以使用$message = rtrim($message, ',');
.
或者,您可以这样做:
foreach ($hello as $key => $value){
if (key($hello) !== 0) {
$message .= ",";
}
$message .= $value;
}