duanjiao3754 2014-06-05 18:14
浏览 83
已采纳

PHP While循环处理循环中的最后一项

I have the following code:

$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]."],";

    }

This works fine, but what I am struggling with is that I need the echo to be different the for the last one in the loop. It needs to be (the comma is missing after the ] for reference):

    echo "['".$sd."',  ".$row6[1]."]";  

I've been trying to do a count of the number of arrays but cannot get that to work. Any suggestions welcomed.

  • 写回答

1条回答 默认 最新

  • douhuan6305 2014-06-05 18:17
    关注

    You can get the total number of rows and define a counter. After that you can compare them in the loop :

    $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++;
    }
    

    Or you can do something like this using implode() :

    $final = array();
    while($row6 = $result6->fetch_row()){
        $dt = new DateTime($row6[0]);
        $final[] =  "['" . $dt->format('M j') . "',  ".$row6[1]."]";
    }
    echo implode(', ', $final);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥50 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗