Create a comma-separated string from a single column of an array of objects

前端 未结 14 1325
醉话见心
醉话见心 2020-11-30 07:36

I\'m using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.

My loop is just simple, as

相关标签:
14条回答
  • 2020-11-30 08:23
    $arraySize = count($results);
    for($i=0; $i<$arraySize; $i++)
    {
      $comma = ($i<$arraySize) ? ", " : "";
      echo $results[$i]->name.$comma;
    }
    
    0 讨论(0)
  • 2020-11-30 08:24

    Better:

    $resultstr = array();
    foreach ($results as $result) {
      $resultstr[] = $result->name;
    }
    echo implode(",",$resultstr);
    
    0 讨论(0)
提交回复
热议问题