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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示