从while循环中删除最后一个逗号

时间:2014-01-03 16:34:52

标签: php

我的代码产生了这样的输出

Title1,1,Title2,2,

如何从此删除最后一个逗号?

$comma = ",";

$query = "SELECT name, listid FROM playlist ORDER BY id DESC";
$result = $mysqli->query($query);

while(list($name, $listid) = $result->fetch_row()) {
    echo $name;
    echo $comma;
    echo $listid;
echo $comma;
}

7 个答案:

答案 0 :(得分:8)

不要手动回复逗号。只需制作一个数组,然后implode

echo implode(',', array($name, $listid));

答案 1 :(得分:8)

$lines = array();

while(list($name, $listid) = $result->fetch_row()) {
    $lines[] = "$name,$listid";
}

echo implode(',', $lines);

答案 2 :(得分:2)

使用修剪

<?php
$str = "1,2,3,4,5,";
echo trim($str, ",");

<强>输出

1,2,3,4,5

答案 3 :(得分:1)

你可以试试这个:

$query = "SELECT name, listid FROM playlist ORDER BY id DESC";
$result = $mysqli->query($query);

$data = array();
while(list($name, $listid) = $result->fetch_row()) {
    $data[] = $name.",".$listid;
}

echo implode(',', $data);

答案 4 :(得分:1)

试试这个

 $comma = ",";
    $html = ""; 

    $query = "SELECT name, listid FROM playlist ORDER BY id DESC";
    $result = $mysqli->query($query);

    while(list($name, $listid) = $result->fetch_row()) {
        $html .= $name.$comma.$listid.$comma;   
    }

   echo substr($html, 0, strlen($html) - 2);

答案 5 :(得分:0)

我建议选择约瑟夫·西尔伯的答案,尽管这样可行:

$comma = ",";
$k=0;
$query = "SELECT name, listid FROM playlist ORDER BY id DESC";
$result = $mysqli->query($query);
while(list($name, $listid) = $result->fetch_row()) {
    if($k!=0){
     echo $comma;
    }
    echo $name;
    echo $comma;
    echo $listid;        
    $k++;
}

答案 6 :(得分:0)

$result = mysqli_query($con,$query);
$num_rows= mysqli_num_rows($result);
$ctr=0;
while($row=mysqli_fetch_array($result)){
$ctr++;
    echo $row['example'];
    if($ctr!=$num_rows){
        echo ',';}
    else{
        echo '';
    }
}