如何:从具有特定属性值的数组中删除对象并生成新数组


How to: remove object from array that has certain property value and crete new array as result

我有一个这样的数组:

Array
(
[0] => stdClass Object
(
[id] => 227
[catid] => 10
)
[1] => stdClass Object
(
[id] => 228
[catid] => 29
)
[2] => stdClass Object
(
[id] => 229
[catid] => 11
)
[3] => stdClass Object
(
[id] => 230
[catid] => 29
)
)

现在我尝试从数组中删除一些对象基于catid:

foreach ($myarray as $item) {
    if ($myarray->catid != 29) unset($item);
}

但是如何从上面的foreach创建新的数组?基本上,我想要一个新数组,它只包含catid = 29:

的对象
Array
(
[0] => stdClass Object
(
[id] => 228
[catid] => 29
)
[1] => stdClass Object
(
[id] => 230
[catid] => 29
)
)

可以使用array_filter;

$filtered = array_filter($myarray, function($item){ return $item->catid === 29; });

,但这不会从原始数组中删除对象。要同时执行这两项操作,只需将该操作添加到循环中即可。

foreach ($myarray as $key => $value) {
    if ($value->catid == 29) {
        $new_array[] = $value;
        unset($myarray[$key]);        
    }
}

foreach()复制要迭代的数组元素。您的unset()正在取消对副本的设置,而不是原来的。

你想要的

foreach($arr as $key => $val) {
   if($val ...) {
      unset($arr[$key]);
   }
}

您可以尝试使用array_filter() &array_map()像这样

//$arr = your array;
$new_array = array_filter($arr, function($v){ return $v->catid == 29 ? $v : false; });

$new_array = array_filter(array_map(function($v){ return $v->catid == 29 ? $v : '';}, $arr));