我有以下代码:
$query6 = "SELECT TIMESTAMP As sDate, COUNT( TIMESTAMP ) AS Total
FROM tresults GROUP BY TO_DAYS( timestamp ) ";
$result6 = $mysqli->query($query6);
while($row6 = $result6->fetch_row())
{
$dt = new DateTime($row6[0]);
$sd = $dt->format('M j');
echo "['".$sd."', ".$row6[1]."],";
}
这很好用,但我正在努力的是我需要echo
与循环中的最后一个不同。它必须是(]
之后缺少逗号):
echo "['".$sd."', ".$row6[1]."]";
我一直在尝试计算数组的数量,但无法实现这一点。欢迎任何建议。
答案 0 :(得分:2)
您可以获取总行数并定义计数器。之后,您可以在循环中比较它们:
$result6 = $mysqli->query($query6);
$num = $resut6->num_rows;
$i = 0;
while($row6 = $result6->fetch_row())
{
if($num != $i){
/* code for all elements except the last one*/
} else {
/* code for the last element*/
}
$i++;
}
或者您可以使用implode()执行此类操作:
$final = array();
while($row6 = $result6->fetch_row()){
$dt = new DateTime($row6[0]);
$final[] = "['" . $dt->format('M j') . "', ".$row6[1]."]";
}
echo implode(', ', $final);