You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过foreach循环过滤stdClass数组,仅保留status=Active的对象

问题描述

需求:过滤包含stdClass对象的数组,仅保留status属性为Active的对象。

现有数据:

$newresults = [
    1 => (object)[
        'id' => 30508,
        'status' => 'Active'
    ],
    2 => (object)[
        'id' => 30509,
        'status' => 'InActive'
    ],
    3 => (object)[
        'id' => 30510,
        'status' => 'Active'
    ]
];

当前尝试的代码存在问题:

foreach ($newresults as $key => $value) {
    if($value->status == 'Inactive')
        unset($newresults[$key]);

    }

    $newresults[]=$value;
}
return $newresults;

问题点:

  • 大括号匹配错误,foreach的闭合逻辑混乱
  • 大小写不匹配:判断条件里的'Inactive'和数据里的'InActive'大小写不一致
  • 循环末尾错误地将当前$value追加回数组,直接导致过滤失效

期望输出:

[
    1 => (object)[
        'id' => 30508,
        'status' => 'Active'
    ],
    2 => (object)[
        'id' => 30510,
        'status' => 'Active'
    ]
]
正确实现方案

方法一:使用foreach创建新数组

初始化空数组,遍历原数组时筛选符合条件的对象加入新数组:

$filteredResults = [];
foreach ($newresults as $item) {
    // 严格匹配大小写与数据一致
    if ($item->status === 'Active') {
        $filteredResults[] = $item;
    }
}
return $filteredResults;

如果需要保留原数组的键名,修改为:

$filteredResults = [];
foreach ($newresults as $key => $item) {
    if ($item->status === 'Active') {
        $filteredResults[$key] = $item;
    }
}
// 若需要重置连续数字键名,可调用array_values
// $filteredResults = array_values($filteredResults);
return $filteredResults;

方法二:使用array_filter简化代码

利用PHP内置的array_filter函数,通过匿名函数定义过滤规则:

$filteredResults = array_filter($newresults, function($item) {
    return $item->status === 'Active';
});
// 如需重置键名,调用array_values
// $filteredResults = array_values($filteredResults);
return $filteredResults;

内容的提问来源于stack exchange,提问作者Troy Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:50:40