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)
请注意主要答案。
和
[['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)