简单的问题;如何从foreach()中删除正确的数组?
foreach ( $items as $e):
if ( $e['seat'] == $users[$clientID]['seat']):
//It's done, delete it.
unset ( $e );
endif;
endforeach;
未设置($ e)似乎无法正常工作。从正确的索引中删除正确的数组的正确解决方案是什么?
答案 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($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;