【问题标题】:Delete the index array from foreach?从foreach中删除索引数组?
【发布时间】:2012-12-27 19:56:57
【问题描述】:

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

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

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

【问题讨论】:

标签: php


【解决方案1】:

这是 xbonez 给出的 for 循环的替代方案,也可以传递 key 值:

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

我更喜欢这个版本,不过没关系!

【讨论】:

    【解决方案2】:

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

    for($i = 0; $i < count($items); $i++) {
       if ($items[$i]['seat'] == $users[$clientID]['seat']) {
          unset($items[$i])
       }
    }
    

    【讨论】:

    • for ($arr as $key =&gt; $val) 会更好,因为您的答案仅限于非关联数组。
    【解决方案3】:

    尝试类似:

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

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2012-05-03
      • 2015-07-27
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      相关资源
      最近更新 更多