在 foreach 循环中取消设置数组元素
我正在 foreach 循环内通过引用访问数组,但 unset() 函数似乎不起作用:
foreach ( $this->result['list'] as &$row ) {
if ($this_row_is_boring) {
unset($row);
}
}
print_r($this->result['list']); // Includes rows I thought I unset
想法?谢谢!
我正在 foreach 循环内通过引用访问数组,但 unset() 函数似乎不起作用:
foreach ( $this->result['list'] as &$row ) {
if ($this_row_is_boring) {
unset($row);
}
}
print_r($this->result['list']); // Includes rows I thought I unset
想法?谢谢!
您正在取消设置引用(断开引用)。您需要根据键取消设置:
foreach ($this->result['list'] as $key => &$row) {
if ($this_row_is_boring) {
unset($this->result['list'][$key]);
}
}
foreach ($this->result['list'] as $key => &$row) {
if ($this_row_is_boring) {
unset($this->result['list'][$key]);
}
}
unset($row);
请记住:如果将 带有引用的 a,则应使用 unset 来取消引用,这样就不会在其上复制下一个引用。更多信息foreachforeach