从foreach中删除索引数组?

时间:2013-01-13 21:49:33

标签: php

简单的问题;如何从foreach()中删除正确的数组?

foreach ( $items as $e):
    if ( $e['seat'] == $users[$clientID]['seat']):
        //It's done, delete it.
        unset ( $e );
    endif;
endforeach;

未设置($ e)似乎无法正常工作。从正确的索引中删除正确的数组的正确解决方案是什么?

3 个答案:

答案 0 :(得分:4)

这是xbonez给出的for循环的替代方法,通过传递key值:

foreach ( $items as $key => $e):
    if ( $e['seat'] == $users[$clientID]['seat']):
        //It's done, delete it.
        unset ( $items[$key] );
    endif;
endforeach;

我更喜欢这个版本,但这并不重要!

答案 1 :(得分:1)

unset($e)中执行foreach取消设置变量$e,而不是它所代表的数组中的项目。您需要为此

使用常规for循环
for($i = 0; $i < count($items); $i++) {
   if ($items[$i]['seat'] == $users[$clientID]['seat']) {
      unset($items[$i])
   }
}

答案 2 :(得分:1)

尝试类似:

foreach ($items as &$e):
    if ($e['seat'] == $users[$clientID]['seat']):
        //It's done, delete it.
        unset ($e);
    endif;
endforeach;