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

PHP如何过滤关联数组数组,提取type为Beverage的元素?

提取指定类型的数组元素

你可以用array_filter()函数配合匿名函数实现需求,直接在回调函数里判断每个子数组的type字段是否等于Beverage就行,示例代码如下:

$products = [
    ['id' => 1, 'prod_name' => 'Coffee', 'type' => 'Beverage'],
    ['id' => 2, 'prod_name' => 'Vegetable', 'type' => 'Food'],
    ['id' => 3, 'prod_name' => 'Orange Juice', 'type' => 'Beverage'],
];

// 过滤出type为Beverage的元素
$beverages = array_filter($products, function($item) {
    return $item['type'] === 'Beverage';
});

print_r($beverages);

运行后输出的结果会是:

Array ( 
    [0] => Array ( 
        [id] => 1 
        [prod_name] => Coffee 
        [type] => Beverage 
    )
    [2] => Array ( 
        [id] => 3 
        [prod_name] => Orange Juice 
        [type] => Beverage 
    )
)

如果需要重新索引数组(让键从0开始连续排列),可以在过滤后加上array_values()处理:

$beverages = array_values(array_filter($products, function($item) {
    return $item['type'] === 'Beverage';
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:00:53