PHP foreach变量范围问题
我有一个充满关联数组的数组,如下所示:PHP foreach变量范围问题,php,Php,我有一个充满关联数组的数组,如下所示: $arr = [ ['title' => 'My title', 'content' => 'lorem ...', comments: 'lorem ipsum'], ['title' => 'My title 2', 'content' => 'lorem ...'], ['title' => 'My title 3', 'content' => 'lorem ...'], ['title' =>
$arr = [
['title' => 'My title', 'content' => 'lorem ...', comments: 'lorem ipsum'],
['title' => 'My title 2', 'content' => 'lorem ...'],
['title' => 'My title 3', 'content' => 'lorem ...'],
['title' => 'My title 4', 'content' => 'lorem ...', comments: 'lorem ipsum'],
];
如您所见,其中一些没有注释
问题是,我有这样一个foreach循环:
<?php foreach($arr as $key => $value){
extract($value);
?>
<div>
...etc
<?php if($comment): ?>
<span><?= $comment ?></span>
<?php endif; ?>
</div>
<?php } ?>
等
在第二次迭代中,变量$comments
现在保存数组中第一项的值,因为它在关联数组中找不到属性,而使用最后一项,从而中断了if
语句
是否有任何方法可以避免这种情况,而无需向原始数组添加注释:null
或其他内容?只需使用检查变量$elem['comments']
是否存在:
<div>
<?php
foreach($arr as $key => $elem){
if(isset($elem['comments'])){
// Comments exists here
echo "<span>".$elem['comments']."</span>";
}else{
// Comments do not exists here, so don't echo anything
}
}
?>
</div>
请注意:
对于对应于NULL的数组键,isset()不返回TRUE
值,而数组_key_exists()不存在
因此,在您的用例中,我建议您使用isset
放弃现有的注释
键和null
值,就像注释
键不存在一样。只需使用检查变量$elem['comments']
是否存在:
<div>
<?php
foreach($arr as $key => $elem){
if(isset($elem['comments'])){
// Comments exists here
echo "<span>".$elem['comments']."</span>";
}else{
// Comments do not exists here, so don't echo anything
}
}
?>
</div>
请注意:
对于对应于NULL的数组键,isset()不返回TRUE
值,而数组_key_exists()不存在
因此,在您的用例中,我建议您使用
isset
放弃现有的comments
键和null
值,就像comments
键不存在一样。不使用extract。正确命名变量。您的IDE也会为此感到高兴。如果PHP中的(isset($value['comment']){…}
变量的作用域是函数,而不是迭代块。因此,循环重复时,循环中设置的变量不会消失。不要使用extract()
。你不需要它。永远不需要extract()
,当使用“c-o-r-e-c-t-l-y”时,会很快导致无法维护的代码,因此授予终身作业不使用extract。正确命名变量。您的IDE也会为此感到高兴。如果PHP中的(isset($value['comment']){…}
变量的作用域是函数,而不是迭代块。因此,循环重复时,循环中设置的变量不会消失。不要使用extract()
。你不需要它。永远不需要extract()
,当使用-c-o-r-e-c-t-l-y时,很快就会产生无法维护的代码,从而授予终身工作