Nested foreach loop, break inside loop

我与影子孤独终老i 提交于 2019-12-11 04:21:28

问题


I try to create a list with nested foreach loop. First loop is looping some numbers, second loop is looping dates. I want to write one number to one date. So there is a another function to check that. But the result is numbers writes on dates multiple times.

Out is something like that :

number 5 is on 2013.01.15;
number 5 is on 2013.01.16;
number 5 is on 2013.01.17;
number 6 is on 2013.01.15;
number 6 is on 2013.01.17;

The code :

function create_event($numbers,$available_dates) {
  foreach($numbers as $number) {
    foreach($avaliable_dates as $av_date) {

      $date_check= dateCheck($av_date,$number);

      if ($date_check == 0) {
        echo "number ".$number." is on ".$av_date;
        break;
      } else {
        $send_again[] = $number;
      }

    }
  }
  create_event($send_again,$avaliable_dates);
}

I think inside loop is not break.


回答1:


Can you check something like this:

function create_event($numbers,$available_dates) {
    foreach ($numbers as $number) {
        foreach ($available_dates as &$av_date) {
            if (dateCheck($av_date, $number) == 0) {
                unset($av_date);
                break;
            }
        }
    }
}



回答2:


Your break; should break inner foreach loop!
The only reason for such behavior I see is repeating numbers in you array!(E.g. $numers=array(5,5,5,6,6); )
Try to insert: $numbers=array_unique($numbers); before your outer foreach loop
If you need to break both loops(inner and outer) write break 2; instead of break;



来源:https://stackoverflow.com/questions/14341395/nested-foreach-loop-break-inside-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!