具有for for inside的Foreach不会迭代每个元素

时间:2013-10-17 12:49:29

标签: cakephp loops for-loop foreach cakephp-2.3

这是循环:

         foreach($event['Event']['user_id'] as $employee){


     for($date; $date <= $end_date; $date = strtotime("+1 day", $date))
     {
         if(strpos($weekdays, date("N", $date)) !== false){
             $real_date = date("Y-m-d", $date);
             $event['Event']['date'] = $real_date;
             $event['Event']['user_id'] = $employee;
             $this->Event->create();
             $this->Event->save($event);
            debug($event['Event']['user_id']);           
         }
     }

    }

* $ event ['Event'] ['user_id'] *的内容如下:

array(
(int) 0 => '23',
(int) 1 => '24',
(int) 2 => '27',
(int) 3 => '28')

如果我尝试在for循环之前打印每个 $ employee ,我会打印所有四个记录,但for循环仅应用于第一个记录。 非常感谢任何帮助。

编辑:添加了 pr($ event)

的结果
Array([Event] => Array
    (
        [project_id] => 62
        [user_id] => Array
            (
                [0] => 23
                [1] => 24
                [2] => 27
                [3] => 28
                [4] => 29
            )

        [hours] => 4
        [minutes] => 0
        [assignment] => 
        [material] => 
        [date] => 2013-10-6
        [start_time] => Array
            (
                [hour] => 09
                [min] => 00
            )

        [finish_time] => Array
            (
                [hour] => 13
                [min] => 00
            )

        [repeat] => 0
        [finish_date] => 
        [weekdays] => 
    )

1 个答案:

答案 0 :(得分:1)

让我们看看,在for的第一个循环中,您可以执行此操作

 for($date; $date <= $end_date; $date = strtotime("+1 day", $date))
 {
     if(strpos($weekdays, date("N", $date)) !== false){
         $real_date = date("Y-m-d", $date);
         $event['Event']['date'] = $real_date;
         $event['Event']['user_id'] = $employee;
         $this->Event->create();
         $this->Event->save($event);
        debug($event['Event']['user_id']);           
     }
 }

该特定情况的$employee数组是23(按您发布的示例)。请注意if语句中的特定行。

$event['Event']['user_id'] = $employee;

基本上,$event['Event']['user_id']不再是

$event['Event']['user_id'] = array(
(int) 0 => '23',
(int) 1 => '24',
(int) 2 => '27',
(int) 3 => '28')

但是

$event['Event']['user_id'] = 23;

代替。因此,foreach函数仅适用于第一个记录,然后停止。 我不建议更改foreach内的foreach参数(就像在这种情况下一样),它总是(或几乎总是)导致混淆。

由于我不知道你试图用这个函数做什么,我不能给你更多的建议,但重新考虑解决这个问题的逻辑。也许像

这样的简单变量
$users = $event['Event']['user_id'];
foreach ($users as $employee) {
    /* the rest remains the same*/
}

就足够了。