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

PHP中如何筛选出color为Yellow且quantity最小的数组元素

筛选指定颜色且数量最小的数组元素

原始数组

Array
(
    [0] => Array
        (
            [color] => Yellow
            [name] => Banana
            [quantity] => 124
        )
    [1] => Array
        (
            [color] => Red
            [name] => Cherry
            [quantity] => 24
        )
    [2] => Array
        (
            [color] => Yellow
            [name] => Apple
            [quantity] => 224
        )

)

筛选需求

  • color 为 Yellow
  • quantity 值最小

预期结果

Array
(
    [0] => Array
        (
            [color] => Yellow
            [name] => Banana
            [quantity] => 124
        )    
)

你的现有代码

$min = array_reduce($array, function($min, $details) {
  return min($min, $details['quantity']);
}, PHP_INT_MAX);

修改方案

你的现有代码没有过滤color为Yellow的条件,会把所有元素的quantity纳入比较,导致得到的最小值不符合需求。可以通过两种方式解决:

方式一:先过滤再找最小值

先筛选出所有color为Yellow的元素,再从中找出quantity最小的项:

// 筛选颜色为Yellow的元素
$yellowItems = array_filter($array, function($item) {
    return $item['color'] === 'Yellow';
});

// 找出其中quantity最小的元素
$minYellowItem = array_reduce($yellowItems, function($carry, $item) {
    return ($carry === null || $item['quantity'] < $carry['quantity']) ? $item : $carry;
}, null);

// 整理成预期的数组格式
$result = $minYellowItem ? [$minYellowItem] : [];

方式二:一次遍历完成筛选与找最小值

在array_reduce中同时判断颜色条件并比较数量,减少一次数组遍历:

$minYellowItem = array_reduce($array, function($carry, $item) {
    // 跳过非Yellow的元素
    if ($item['color'] !== 'Yellow') {
        return $carry;
    }
    // 更新为更小数量的元素
    if ($carry === null || $item['quantity'] < $carry['quantity']) {
        return $item;
    }
    return $carry;
}, null);

// 整理成预期格式
$result = $minYellowItem ? [$minYellowItem] : [];

两种方式最终都会得到你需要的结果,方式二更适合处理大型数组,效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:17:00