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

如何在PHP中根据给定数量匹配moq获取对应costunit值

数组取值问题:匹配符合MOQ条件的costunit值

需求与示例

现有一组包含moq(起订量)和costunit(单位成本)的数组,需根据给定采购数量,返回最大的不超过该数量的moq对应的costunit:

  • 数组示例:
Array
(
    [moq] => 1000
    [costunit] => 0.44
)
Array
(
    [moq] => 20000
    [costunit] => 0.33
)
Array
(
    [moq] => 30000
    [costunit] => 0.30
)
  • 示例1:给定数量25000 → 返回0.33
  • 示例2:给定数量1230 → 返回0.44
  • 示例3:给定数量30000 → 返回0.30

原代码问题分析

你提供的PHP代码存在逻辑错误:

$get_prices = array(
  array( 'moq'=> 1000,  'costunit'=> 0.44 ),
  array( 'moq'=> 20000, 'costunit'=> 0.33 ),
  array( 'moq'=> 30000, 'costunit'=> 0.30 ),
);
$get_quantity = 30000;
foreach($get_prices as $get_price){

  if($get_price['moq'] >= $get_quantity){
    echo '<pre>';
        print_r($get_price['costunit']);
    echo '</pre>';
   }
}
  1. 判断条件写反:$get_price['moq'] >= $get_quantity是找大于等于采购量的moq,和需求完全相反;
  2. 未处理“取最大符合条件moq”的逻辑:即使条件写对,原代码会输出所有符合moq <= 采购量的costunit,而我们需要的是最后一个(最大moq对应的)值。

修正后的代码

$get_prices = array(
    array('moq'=> 1000,  'costunit'=> 0.44),
    array('moq'=> 20000, 'costunit'=> 0.33),
    array('moq'=> 30000, 'costunit'=> 0.30),
);
$get_quantity = 25000;
$matched_costunit = null;

// 确保数组按moq升序排列(原数组已有序可省略此步骤)
usort($get_prices, function($a, $b) {
    return $a['moq'] - $b['moq'];
});

foreach($get_prices as $get_price) {
    if($get_price['moq'] <= $get_quantity) {
        // 更新为当前符合条件的单位成本,最终保留最大moq对应的值
        $matched_costunit = $get_price['costunit'];
    } else {
        // 数组升序,后续moq更大,无需继续遍历
        break;
    }
}

echo '<pre>';
print_r($matched_costunit);
echo '</pre>';

代码说明

  1. 排序处理:通过usort确保数组按moq从小到大排列,保证遍历顺序正确;
  2. 遍历逻辑:只要当前moq不超过采购量,就更新匹配的costunit,遍历结束后得到的就是最大符合条件的moq对应的成本;
  3. 提前终止:遇到第一个超过采购量的moq时直接跳出循环,减少不必要的计算;
  4. 边界处理:如果采购量小于所有moq(如500),$matched_costunit会为null,可根据业务需求添加默认值或提示逻辑。

内容的提问来源于stack exchange,提问作者Never Stop Learning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:05:29