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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?