unset()的麻烦

Bre*_*ore 1 php arrays unset

愚弄了插图目的

  • PHP 5.27(必填).
  • 错误报告已启用.

我正在尝试使用数组$unset来取消设置关联数组$list值,如果其中一个属性$list['id'] 存在于数组中$unset.

但是,我很难理解这里的结果:

<?php
$list = array(
  array(
    'id' => 'foo'
  ),
  array(
    'id' => 'bar'
  ),
  array(
    'id' => 'baz'
  ),
  array(
    'id' => 'quix'
  )
);

$unset = array(
  'foo',
);

for ($i=0; $i < count($list); $i++) { 
  echo "Itteration: {$i}" . '<br />';
  echo "Contest ID: {$list[$i]['id']}" . '<br />';
  echo 'Not in Array: ', (!in_array($list[$i]['id'], $unset)) ? 'True' : 'False';

  unset($list[$i]); // Trouble Section
  echo '<br /><br />';
}
Run Code Online (Sandbox Code Playgroud)

输出:

Itteration: 0
Contest ID: foo
Not in Array: False

Itteration: 1
Contest ID: bar
Not in Array: True
Run Code Online (Sandbox Code Playgroud)

无论$unsetI中的值的数量是多少,只能成功运行2次迭代.

当我删除时,unset($list[$i]);我们成功迭代$list:

Itteration: 0
Contest ID: foo
Not in Array: False

Itteration: 1
Contest ID: bar
Not in Array: True

Itteration: 2
Contest ID: baz
Not in Array: True

Itteration: 3
Contest ID: quix
Not in Array: True
Run Code Online (Sandbox Code Playgroud)

我无法在文档中找到解释为什么会发生这种情况的解释.文档谈论的唯一警告是unset在全局变量函数中使用.我甚至unset($GLOBALS['list'][$i])只是为了好玩而尝试,结果没有变化.

我在这里错过了什么?

Nie*_*sol 7

这是因为count($list)删除项目时会不断变小.

尝试 foreach($list as $i=>$item) {