在 foreach 循环内取消设置数组元素 [英] Unset an array element inside a foreach loop

查看:30
本文介绍了在 foreach 循环内取消设置数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 foreach 循环中通过引用访问数组,但 unset() 函数似乎不起作用:

I'm accessing an array by reference inside a foreach loop, but the unset() function doesn't seem to be working:

foreach ( $this->result['list'] as &$row ) {
    if ($this_row_is_boring) {
        unset($row);
    }
}

print_r($this->result['list']); // Includes rows I thought I unset

想法?谢谢!

推荐答案

您正在取消设置引用(破坏引用).您需要根据键取消设置:

You're unsetting the reference (breaking the reference). You'd need to unset based on a key:

foreach ($this->result['list'] as $key => &$row) {
    if ($this_row_is_boring) {
        unset($this->result['list'][$key]);
    }
}

这篇关于在 foreach 循环内取消设置数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆