如何从foreach循环中的数组中删除对象?

aba*_*aba 133 php arrays foreach unset

我遍历一个对象数组,并希望根据它的'id'属性删除其中一个对象,但我的代码不起作用.

foreach($array as $element) {
    foreach($element as $key => $value) {
        if($key == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($element);//this doesn't work
            unset($array,$element);//neither does this
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么建议.谢谢.

pro*_*son 215

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在同一个数组的foreach循环中删除数组元素是否安全? (60认同)
  • @Oliver:通常它会产生意想不到的行为,但你可以安全地使用foreach在php上.在这里阅读一下测试:http://php.net/manual/en/control-structures.foreach.php#88578 (23认同)
  • @htafoya你不能只做`if(isset($ element ['id'])&& $ element ['id'] =='searching_value'){unset($ array [$ elementKey]); 我想当时我只是复制并修改了他的代码,以向他展示如何正确地"取消设置". (3认同)
  • @Paritosh 我知道你很久以前发布过这个,但这是因为 PHP 使用关联数组。所以你有一个被删除的索引:它被编码为 JSON 作为一个对象。有道理,因为关联数组是一个“字典”。可能会帮助来的人。 (2认同)

mag*_*nes 5

请注意主要答案。

[['id'=>1,'cat'=>'vip']
,['id'=>2,'cat'=>'vip']
,['id'=>3,'cat'=>'normal']
Run Code Online (Sandbox Code Playgroud)

并调用该函数

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'cat' && $value == 'vip'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

它返回

[2=>['id'=>3,'cat'=>'normal']
Run Code Online (Sandbox Code Playgroud)

代替

[0=>['id'=>3,'cat'=>'normal']
Run Code Online (Sandbox Code Playgroud)

这是因为 unset 不会重新索引数组。

它重新索引。(如果我们需要的话)

$result=[];
foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        $found=false;
        if($valueKey === 'cat' && $value === 'vip'){
            $found=true;
            $break;
        } 
        if(!$found) {
           $result[]=$element;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 要重新索引数组,您可以使用 `$array = array_values($array);` (2认同)