【发布时间】:2026-01-17 04:35:01
【问题描述】:
在 PHP 中,循环中定义的变量不是循环的局部变量。有什么方法可以销毁/取消设置每次迭代后声明的每个变量?
如果我在foreach 循环中的if 语句中声明一个变量,问题就来了。这个变量不一定在每次迭代时都声明,所以当我希望它被销毁时,它可能会挂起并具有与上次相同的值!
具体来说,这是我的(简化的)代码。它解析和events.xml 文件,其中包含<event> 元素,这些元素都具有<startDate> 子元素,并且可能有也可能没有<endDate> 子元素,然后形成html 显示所有循环后的事件。
<html>
<?php
$events = simplexml_load_file("events.xml");
foreach ($events as $value):
// get the start date of the current event from the xml file
$startDate = strtotime($value->startDate);
// get the end date if it exists (it might not)
$endDate = strtotime($value->endDate);
// get day of the week from the start date
$startDay = date("D", $startDate);
if ($endDate) {
$endDay = date("D", $endDate);
$dash = "-";
}
?>
<div class="event"> <!-- this is still in the foreach loop -->
<!-- insert the start day (always) followed by a dash and end day (if they exist) -->
<?php echo $startDay, $dash, $endDay; ?>
</div>
<?php endforeach; ?>
</html>
问题是,如果在events.xml 文件中,我有一个带有结束日期的事件,然后是一个没有结束日期的事件,后者的 div 将具有前者的结束日期(因为 @987654329 @ 变量未设置),当我根本不希望它有结束日期时。 (如果 xml 文件顶部有没有结束日期的事件,则其 div 将没有结束日期。)
有趣的是,对于没有结束日期的事件,$endDate 变量似乎在这一行被破坏:$endDate = strtotime($value->endDate);,大概是因为它试图从 xml 中读取它但什么也没找到。但是如果我将$endDay 声明放在if 语句之外,那么默认情况下它会转到01,这是我不想要的。
【问题讨论】: