除了最后一个条目,PHP用逗号分隔条目?

时间:2011-08-06 01:04:08

标签: php

我正在使用循环从数据库中获取记录。我想要它,所以每条记录后都有一个逗号,除非它是最后一条记录,或者只显示一条记录。

这是我的部分代码:

while($medals = $db->fetch_array($query))
{
    if($medals['post_count'] != "")
    {
        $requirements = $medals['post_count']." posts";
    }
    if($medals['time_registered'] != "")
    {
        $requirements .= "Registered for ".$medals['time_registered']." days";
    }
    if($medals['thread_count'] != "")
    {
        $requirements .= $medals['thread_count']." threads";
    }           
    if($medals['num_reps'] != "")
    {
        $requirements .= $medals['num_reps']." positive reputations";
    }
}

我该如何做到这一点?

感谢。

1 个答案:

答案 0 :(得分:1)

while($medals = $db->fetch_array($query))
{
    $requirements = array();
    if($medals['post_count'] != "")
    {
        $requirements[] = $medals['post_count']." posts";
    }
    if($medals['time_registered'] != "")
    {
        $requirements[] = "Registered for ".$medals['time_registered']." days";
    }
    if($medals['thread_count'] != "")
    {
        $requirements[] = $medals['thread_count']." threads";
    }           
    if($medals['num_reps'] != "")
    {
        $requirements[] = $medals['num_reps']." positive reputations";
    }
    $requirements = implode(', ',$requirements);
}

或者你需要在行之间使用逗号?