为了账号安全,请及时绑定邮箱和手机立即绑定

PHP foreach变量范围问题

PHP foreach变量范围问题

PHP
明月笑刀无情 2023-05-26 16:08:36
我有一个充满关联数组的数组,如下所示:$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'],];如您所见,其中一些没有comments.问题是,我有一个这样的 foreach 循环:<?php foreach($arr as $key => $value){  extract($value);?>  <div>    ...etc    <?php if($comment): ?>       <span><?= $comment ?></span>    <?php endif; ?>  </div><?php } ?>在第二次迭代中,变量$comments现在保存数组中第一项的值,因为它没有在关联数组中找到该属性,而是使用最后一个,从而破坏了语句if。有什么办法可以避免这种情况而不必comments: null在原始数组中添加 a 或其他东西吗?
查看完整描述

1 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

只需使用isset来检查变量是否$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>

或者使用array_key_exists检查comments键是否在数组中elem


<?php

foreach($arr as $key => $elem){

    if(array_key_exists('comments', $elem)) {

        // Comments exists here

        echo "<span>".$elem['comments']."</span>";

    }else{

        // Comments do not exists here, so don't echo anything

    }

}

?>

请注意:


对于对应于 NULL 值的数组键,isset() 不会返回 TRUE,而 array_key_exists() 会。


因此,在您的用例中,我建议您isset在丢弃具有值的现有comments键时使用null,就像comments键不存在一样。


查看完整回答
反对 回复 2023-05-26
  • 1 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信