不添加应该添加到if语句中的列表的内容

I am looping through a list of objects: however a couple of times (and always for the same ones) it will not work as expected.

I am trying to add the teacher object to the list if its ID does not match he Teacher ID of a previous Lesson in that time period (SubBlock/SB). The one particular teacher that it doesn't seem to like is a teacher who is free to teach all the lessons, out of the 6.

I am trying to get it to pick that teacher and it works on attempt 1,3,5 but not 2,4,6.

Here is the relevant function:

function getRelaventFreeTeachers(&$PossibleTeachers, $Teachers, $Lessons, $SB){
    foreach ($Teachers as $TeacherID){
    $Usability = 1;
    foreach ($Lessons as $Lesson){
        $LT = $Lesson->getLessonTeacher();
        $T = $TeacherID->getTID();
        $LSB = $Lesson->getBlock();
        if ($LT != $T){
            if ($LSB != $SB){
                $Usability = 1;
            }
        }else{
            $Usability = 0;
        }
     }
     if ($Usability == 1){
         array_push($PossibleTeachers, $TeacherID);
     }
   }
}

The question is not really very clear on the condition to add or not add a possible teacher, but some things seems wrong in the code:

  • Once the variable $Usability is set to 0, your code does not prevent it from getting 1 again in a subsequent iteration of the inner loop. That does not look right. You should exit the inner loop as soon as you detect it is not OK.

  • The case where you set $Usability to 1 is therefore not necessary: it already is 1 from the start, and when it gets 0 you exit. You wrote of a condition where the teacher should only be checked for a particular period. If I interpret that correctly then the code might need to look like this:

    if ($LT == $T && $LSB == $SB) { // Is the second condition indeed what you want?
        $Usability = 0;
        break;
    }