Echo a comma on all but the last value? (result from mysql_fetch_array)

后端 未结 11 1945
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 22:56

How do I echo a comma on all but the last value? Here\'s my code:

while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {

    ECHO $servdescarrayrow         


        
相关标签:
11条回答
  • 2020-12-21 23:32

    This should work:

    $i = 0;
    $c = mysql_num_rows ( 
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
        $i++;
        if ( $i < mysql_num_rows ) echo $servdescarrayrow['serv_desc'].",";
        else echo $servdescarrayrow['serv_desc'];
    }
    
    0 讨论(0)
  • 2020-12-21 23:33
    $started = null;
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) 
    {
      ECHO $started.$servdescarrayrow['serv_desc'];
      if ( ! isset($started))
      {
        $started = ",";
      }
    }
    
    0 讨论(0)
  • 2020-12-21 23:34
    $count = 0;
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
        if ($count++ > 0) echo ",";
        echo $servdescarrayrow['serv_desc'];
    }
    
    0 讨论(0)
  • 2020-12-21 23:34
    $out = $mydb->getOne("SELECT group_concat(serv_desc) FROM table");
    

    where $mydb is a database class, getOne() is a helper function returning first col of the first row and group_concat() output is limited to 1024 bytes but can be altered by setting appropriate variable.

    But of course an average enthusiast from this site will always use generic PHP for such a task, as nobody will tell him there are more intelligent ways.

    0 讨论(0)
  • 2020-12-21 23:37

    Another option:

    $values = array();
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
        $values[] = $servdescarrayrow['serv_desc'];
    }
    
    echo implode(',', $values);
    
    0 讨论(0)
  • 2020-12-21 23:37

    Try using rtrim on your output. For example:

    $output = '';
    
    while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {    
        $output .= $servdescarrayrow['serv_desc'].",";
    }
    
    echo rtrim($output, ',');
    
    0 讨论(0)
提交回复
热议问题