dongmei9961 2013-06-13 21:55
浏览 19
已采纳

数组php中值的区别

I'm having issues looping through an array and comparing each value to the next. Currently my function works, but it only compares values in sets of two. For example if in the 'Start' value I had:

1:05am 1:10am 1:30am 1:35am

I would get the results of: 5 minutes (The time between 1:05 and 1:10) and 5 minutes (The time between 1:30 and 1:35)

But I'm missing the time between 1:10 and 1:30. The next loop would give me the time between the next two values, ignoring the time between 1:35 and the next. The function is for silverstripe which uses datalists but the pattern should be the same as any array? Would appreciate any insight.

 function timeCount()
{
    $times = $this->Meetings()->sort('Start');
    $lastTime = null;

    foreach ($times as $time) {
        if ($lastTime == null) {
            $lastTime = $time;
            continue;
        }

        $time = strtotime($time->Start);
        $lastTime = strtotime($lastTime->Start);

        //For debugging
        $diff = round(abs($time - $lastTime) / 60, 2) . " minute | ";

        $lastTime = null;

        var_dump($diff);
    }
}
  • 写回答

1条回答 默认 最新

  • ds42774 2013-06-13 21:59
    关注

    When you do

        $lastTime = null;
    

    It will cause the next iteration of the loop to think it is the first, therefore you're skipping every second comparison.

    function timeCount()
    {
        $times = $this->Meetings()->sort('Start');
        $lastTime = null;
    
        foreach ($times as $time) {
            if ($lastTime == null) {
                $lastTime = $time;
                continue;
            }
    
            $timeVal = strtotime($time->Start);
            $lastTimeVal = strtotime($lastTime->Start);
    
            //For debugging
            $diff = round(abs($timeVal - $lastTimeVal) / 60, 2) . " minute | ";
    
            $lastTime = $time;
    
            var_dump($diff);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥20 sim800c模块 at指令及平台
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计