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

如何使用array_filter或array_intersect按一维数组过滤二维数组指定列

你的写法存在两个问题:

  • array_intersect仅支持对比同维度数组的元素值,无法直接匹配二维数组内指定字段的值
  • $a1是索引数组,不存在$a1['age']这个维度的取值,原有代码逻辑不成立。

你可以组合array_filter+in_array实现需求,示例代码如下:

// 遍历过滤$a1的每一个人员条目
$filtered = array_filter($a1, function($user) use ($a2) {
    // 仅保留年龄在白名单$a2中的条目
    return in_array($user['age'], $a2);
});
// 可选操作:重置数组索引为连续的数字索引,匹配你期望的输出格式
$filtered = array_values($filtered);

print_r($filtered);

运行后输出结果和你预期的完全一致:

Array
(
    [0] => Array
        (
            [name] => james
            [age] => 22
        )
    [1] => Array
        (
            [name] => sarah
            [age] => 35
        )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:45:04