PHP foreach循环记住最后一个循环变量

Good morning/afternoon Y'all,

I am running into a weird issue where it seems that one of my foreach loops is remembering variables from its last loop.

Here is the loop in question:

foreach($result as $obj) {
    $S_MatterNum = $obj['matter_num'];
    $S_SurveyName = $obj['longname'];
    $D_DateSubmit = new datetime($obj['date_submit']);
    $D_DateComp = new datetime ($obj['date_complete']);
    echo "<tr id=" . $S_MatterNum . ">";
    echo '<td>' . $S_MatterNum . '</td>';
    echo '<td>' . $S_SurveyName . '</td>';
    echo '<td>' . $D_DateSubmit->format('d/m/Y') . ' & '. $D_DateComp->format('d/m/Y') .'</td>';
    if (!isset($D_DateComp)){
        $D_DateComp = 'Not Completed Yet';
        echo '<td>' . $D_DateComp . '</td>';
        echo '<td></td>';
    } else {
        echo '<td>' . $D_DateComp->format('d/m/Y'). '</td>';
        echo '<td><button onclick="pullsurvey('.$S_MatterNum.')">Pull</button></td>';
    }
    echo "</tr>";
}

The issue I am having is with the $D_DateComp variable. The loop gets its information from the following:

$SQL = "SELECT * FROM survey_list INNER JOIN survey_names ON survey_list.survey_name = survey_names.shortname";
$result = mysqli_query($con,$SQL);
if ($result === false) {
        echo("Error: " . $SQL . "<br>" . $con->error);
}
if (mysqli_num_rows($result) == 0) {
    $result = mysqli_fetch_all($result,MYSQLI_ASSOC);
}

Now if the date_complete column in the table is NULL (the survey hasn't been completed yet) then $D_DateComp is being set to the last non-NULL occurrence instead of being set to NULL, so it could be being set to the value of $D_DateComp from 5 loops ago.

Is this caused by the way I pull the information out of the database, or is it caused by the way I process the info once it is out?

If the above is a little bit too cryptic I can try and explain all the separate parts and provide screenshots.

You're instantiating a DateTime instance without any sort of condition:

$D_DateComp = new datetime ($obj['date_complete']);

Then you check if this variable is set:

if (!isset($D_DateComp)){

$D_DateComp will always be set, it will be a DateTime instance. Your problem isn't that the variable is sharing the value of the previous iteration, the problem is your condition doesn't match your expectations.

Maybe you should be checking if $obj['date_complete'] is null?