Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP foreach变量范围问题_Php - Fatal编程技术网

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时,很快就会产生无法维护的代码,从而授予终身工作