如何使用逗号组合数组中的所有元素?

nic*_*sen 3 php string while-loop

我知道这个问题已经被问到了很多次.我似乎可以找到解决方案.如果这是简单的方法,请原谅我.

问题是如何访问while循环的结束.

例如

    while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
            $c = $countByMonth["COUNT(id)"];
            echo $c . "," ; 
        }
Run Code Online (Sandbox Code Playgroud)

如何通过逗号分隔while循环的每个值,但当然我不希望逗号位于值的末尾.

提前谢谢你的帮助:)

Nul*_*ion 6

您可以:

1)构建一个字符串,并删除最后一个字符:

$c = '';
while ($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c .= $countByMonth["COUNT(id)"] . ',';
}

$c = substr($c, 0, -1);
echo $c;
Run Code Online (Sandbox Code Playgroud)

2)构建一个数组并使用 implode()

$c = array();
while ($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c[] = $countByMonth["COUNT(id)"];
}

echo implode(',', $c);
Run Code Online (Sandbox Code Playgroud)

提示:您可以在查询中使用别名,例如:SELECT COUNT(id) as count FROM ....然后你可以访问它$countByMonth['count'],看起来更清洁的IMO.


jen*_*ram 5

简单的1解决方案:

$isFirst = true;
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c = $countByMonth["COUNT(id)"];
    if ($isFirst) {
        $isFirst = false;
    } else {
        echo = ', ';
    }
    echo $c; 
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以implode()使用值.或者 - 也许更容易阅读/理解/维护 - 将它全部连接成一个字符串并删除最后一个" ,"(SO吃掉我的空格;字符串是逗号 - 空格):

$list = '';
while($countByMonth = mysql_fetch_array($countByMonthSet)) { 
    $c = $countByMonth["COUNT(id)"];
    $list .= $c . ', '; 
}
echo substring($list, 0, -2); // Remove last ', '
Run Code Online (Sandbox Code Playgroud)

(其他几个答案提出使用累积数组然后使用implode().从性能角度来看,这种方法优于字符串连接.)

1见评论.