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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真