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

如何从PHP多维数组中获取最低折扣价及对应折扣类型或原数组键?

解决多维数组中获取最低价格及对应折扣类型的问题

针对你给出的折扣数组,这里提供几种实用的方法来获取最低价格、对应折扣类型及原数组键:

通过array_column提取价格数组(默认保留原数组键),再找到最小值对应的原键,最后从原数组中获取信息:

// 提取价格数组,保留原数组索引作为键
$priceArray = array_column($discountNew, 'price');
// 找到最低价格对应的原数组键
$lowestKey = array_search(min($priceArray), $priceArray);
// 获取目标数据
$lowestPrice = $discountNew[$lowestKey]['price'];
$lowestType = $discountNew[$lowestKey]['type'];

// 输出结果
echo "最低价格:{$lowestPrice},折扣类型:{$lowestType},原数组键:{$lowestKey}";

方法二:遍历数组实时记录最优值

这种方法仅需遍历一次数组,性能更优,适合处理大数据量:

// 初始化变量
$lowestPrice = PHP_INT_MAX;
$lowestType = '';
$lowestKey = -1;

// 遍历数组,实时更新最小值及对应信息
foreach ($discountNew as $key => $item) {
    if ($item['price'] < $lowestPrice) {
        $lowestPrice = $item['price'];
        $lowestType = $item['type'];
        $lowestKey = $key;
    }
}

// 输出结果
echo "最低价格:{$lowestPrice},折扣类型:{$lowestType},原数组键:{$lowestKey}";

方法三:使用array_reduce函数式处理

通过array_reduce迭代数组,直接返回包含最低价格和类型的元素,若需要原键可在回调中记录:

// 获取包含最低价格和类型的元素
$result = array_reduce($discountNew, function($carry, $item) {
    return ($carry === null || $item['price'] < $carry['price']) ? $item : $carry;
}, null);

// 若需要原数组键,修改回调函数
$resultWithKey = array_reduce($discountNew, function($carry, $item) {
    static $currentKey = 0;
    if ($carry === null || $item['price'] < $carry['price']) {
        $carry = [
            'key' => $currentKey,
            'price' => $item['price'],
            'type' => $item['type']
        ];
    }
    $currentKey++;
    return $carry;
}, null);

// 输出结果
echo "最低价格:{$result['price']},折扣类型:{$result['type']}";
echo "最低价格:{$resultWithKey['price']},折扣类型:{$resultWithKey['type']},原数组键:{$resultWithKey['key']}";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:46:09