在php的循环中摆脱最后一个逗号

时间:2016-06-28 15:27:02

标签: php

我正在尝试发送多个sms并且api的正确格式应该是(00,001,002)但是使用我当前的sql它会产生这样的结果(00,001,002,)

如何更正我的脚本以获得此结果(00,001,002)

$query_rs_p = "SELECT * FROM contacts ORDER BY id DESC";
$rs_p = mysql_query($query_rs_p, $insurance) or die(mysql_error());
$row_rs_p = mysql_fetch_assoc($rs_p);
$totalRows_rs_p = mysql_num_rows($rs_p);
$ph=',';
do {
echo $row_rs_p['phone_number'].$ph;
} while ($row_rs_p = mysql_fetch_assoc($rs_p));

3 个答案:

答案 0 :(得分:2)

不要在循环中回显它,而是将它全部放在一个字符串中。然后在输出之前剪掉最后一个逗号:

$query_rs_p = "SELECT * FROM contacts ORDER BY id DESC";
$rs_p = mysql_query($query_rs_p, $insurance) or die(mysql_error());
$row_rs_p = mysql_fetch_assoc($rs_p);
$totalRows_rs_p = mysql_num_rows($rs_p);
$ph=',';
$string = '';
do {
$string .= $row_rs_p['phone_number'].$ph;
} while ($row_rs_p = mysql_fetch_assoc($rs_p));
$string = rtrim($string, ',');
echo $string;

或者,更好的是,只需在查询中构建此字符串即可。更简单,更清洁:

$query_rs_p = "SELECT group_concat(phone_number) as phine_numbers FROM contacts ORDER BY id DESC";
$rs_p = mysql_query($query_rs_p, $insurance) or die(mysql_error());
$row_rs_p = mysql_fetch_assoc($rs_p);
echo $row['phone_numbers'];

答案 1 :(得分:1)

使用rtrim功能

$rowsphone =  $row_rs_p['phone_number'].$ph;
rtrim($rowsphone,',');

答案 2 :(得分:0)

最直接的可能是做这样的事情:

$output = '';
do {
    if ($output != '')
        $output .= ',';
    $output .= $row_rs_p['phone_number'];
while ($row_rs_p = mysql_fetch_assoc($rs_p);

echo $output;