PHP - remove comma from the last loop

旧城冷巷雨未停 提交于 2020-01-04 05:55:07

问题


I have a PHP while LOOP, and I want to remove last comma , from echo '],'; if it is last loop

            while($ltr = mysql_fetch_array($lt)){
                echo '[';
                echo $ltr['days']. ' ,'. $ltr['name'];
                echo '],';
            }

回答1:


$str = '';
while($ltr = mysql_fetch_array($lt)){
    $str .= '[';
    $str .= $ltr['days']. ' ,'. $ltr['name'];
    $str .= '],';
}

echo rtrim($str, ",");

this will remove the last , from string




回答2:


Create an array with the elements as you go along so that they look like array = ([ELEMENT INFO], [ELEMENT INFO], [ELEMENT INFO]) and then implode the array with a comma.




回答3:


I think the systemic solution is following:

$separator = '';
while($ltr = mysql_fetch_array($lt)){
    echo $separator;
    echo '[';
    echo $ltr['days']. ' ,'. $ltr['name'];
    echo ']';
    if (!$separator) $separator = ', ';
}

No call for count(), no additional iteration of implode(), no additional string operations, ready for any (unpredictable) number of results.




回答4:


$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
    $ltr = $result[$i];
    echo '[';
    echo $ltr['days']. ' ,'. $ltr['name'];
    echo ']';
    if(!count($result)-1 == $i){
        echo ',';
    }
}



回答5:


Check how many entries you have, make a "Counter" and a condition to only put the comma when its not the last loop.




回答6:


$arr = array();
while($ltr = mysql_fetch_array($lt)){
    $arr[] = '[' . $ltr['days'] . ' ,' . $ltr['name'] . ']';
}

echo implode(',', $arr);



回答7:


$res_array = array();

while($ltr = mysql_fetch_array($lt)){
   $res_array[] = '['.$ltr['days']. ' ,'. $ltr['name'].']';
}

$str = implode(",",$res_array);
echo $str; 



回答8:


Save the response as a var instead of echoing it and then remove the final character at the end using substr.

      $response = "";
       while($ltr = mysql_fetch_array($lt)){
            $response .= '[';
            $response .= $ltr['days']. ' ,'. $ltr['name'];
            $response .= '],';
        }
      echo substr($response, 0, -1);



回答9:


//this one works
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
    $ltr = $result[$i];
    echo '[';
    echo $ltr['days']. ' ,'. $ltr['name'];
    echo ']';
    if(count($result)-1 != $i){
        echo ',';
    }
}


来源:https://stackoverflow.com/questions/14701286/php-remove-comma-from-the-last-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!