重复输出数组

时间:2013-09-23 03:16:06

标签: php codeigniter

    $timein_out = $this->time_model->get_timein_out($this->input->get('i'));   

    $total_diff= array();
    $hours = array();
    $mins =array();

    foreach($timein_out as $timetest)
     {
        $total_diff[] = strtotime($timetest["Time_out"]) - strtotime($timetest["Time_in"]);

        for($key=0;$key<count($total_diff);$key++)
        {
            $hours[] = intval(floor($total_diff[$key]/3600));
            $mins[] =  intval(($total_diff[$key]-$hours[$key]*3600)/60); 
        }

     };

     echo json_encode($total_diff); // output: [33600,34560,35160]
     echo json_encode($hours); // [9,9,9,9,9,9]
     echo json_encode($mins); //[20,20,36,20,36,46]

实际输出应为

 echo json_encode($hours); // [9,9,9,]
 echo json_encode($mins); //[20,36,46]

问题:为什么输出重复?我的代码中有什么问题? :(谢谢。

2 个答案:

答案 0 :(得分:3)

可能是你想要内部循环。试试这个。

 foreach($timein_out as $timetest)
 {
    $total_diff[] = strtotime($timetest["Time_out"]) - strtotime($timetest["Time_in"]);

 }
 for($key=0;$key<count($total_diff);$key++)
 {
     $hours[] = intval(floor($total_diff[$key]/3600));
     $mins[] =  intval(($total_diff[$key]-$hours[$key]*3600)/60); 
 }

答案 1 :(得分:1)

可能会unset()尝试$total_diff,如:

foreach($timein_out as $timetest) {
    $total_diff[] = strtotime($timetest["Time_out"]) - strtotime($timetest["Time_in"]);

    for($key=0;$key<count($total_diff);$key++) {
        $hours[] = intval(floor($total_diff[$key]/3600));
        $mins[] =  intval(($total_diff[$key]-$hours[$key]*3600)/60); 
    }
    unset($total_diff);
}