如何从PHP多维数组中获取最低折扣价及对应折扣类型或原数组键?
解决多维数组中获取最低价格及对应折扣类型的问题
针对你给出的折扣数组,这里提供几种实用的方法来获取最低价格、对应折扣类型及原数组键:
方法一:利用array_column+array_search
通过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
相关产品推荐
相关产品推荐

