简体   繁体   中英

Nested foreach loop, break inside loop

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.

Your break; should break inner foreach loop!
The only reason for such behavior I see is repeating numbers in you array!(Eg $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;

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;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM