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

PHP如何基于四维数组最深层列值过滤符合条件的数组元素

PHP多维数组按嵌套分类ID过滤实现方案

错误原因

原有代码直接将二维结构的$value['categories']与整数1做全等判断,类型与值均不匹配,判断永远返回false,因此过滤结果为空数组。

正确实现代码

通用写法(支持单个/多个分类场景)

通过array_column提取所有分类ID后判断目标ID是否存在,兼容性强,无需关心分类数组的长度:

$targetCategoryId = 1;
$filteredArray = array_filter($array, function ($item) use ($targetCategoryId) {
    $categoryIds = array_column($item['categories'], 'id');
    return in_array($targetCategoryId, $categoryIds);
});

简化写法(仅适用于每个元素只有1个分类的场景)

如果确认接口返回的categories永远只有1个元素,可以直接取首个分类的ID判断:

$filteredArray = array_filter($array, function ($item) {
    return $item['categories'][0]['id'] === 1;
});

低版本PHP兼容写法

如果运行环境不支持array_column(PHP 5.5以下版本),可以通过遍历分类数组判断:

$targetCategoryId = 1;
$filteredArray = array_filter($array, function ($item) use ($targetCategoryId) {
    foreach ($item['categories'] as $category) {
        if ($category['id'] === $targetCategoryId) {
            return true;
        }
    }
    return false;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:09:04