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

如何在PHP中通过多维数组搜索获取对应价格

解决方案

步骤1:修正参数定义

首先注意你的参数定义存在语法错误,字符串类型的dm_id和decoration_code需要用引号包裹,否则PHP会将其视为未定义常量:

$dm_id = "LL0007";
$decoration_code = "LL0007C9";
$quantity = 50;

步骤2:筛选匹配的子数组

使用array_filter()函数遍历多维数组,筛选出dm_id和decoration_code完全匹配的子数组:

// 假设你的多维数组名为$decorations
$matchedItem = array_filter($decorations, function($item) use ($dm_id, $decoration_code) {
    return $item['dm_id'] === $dm_id && $item['decoration_code'] === $decoration_code;
});

// 将筛选结果转为索引数组,确保能直接获取第一个匹配项
$matchedItem = reset($matchedItem);

步骤3:匹配对应数量的价格值

遍历子数组中的q1到q6字段,找到与quantity匹配的对应p值:

$price = null;
// 遍历q1-q6的数量区间
for ($i = 1; $i <= 6; $i++) {
    $qKey = "q{$i}";
    $pKey = "p{$i}";
    
    // 跳过q值为0的无效区间
    if ((int)$matchedItem[$qKey] === 0) {
        continue;
    }
    
    // 匹配到对应数量,获取价格
    if ((int)$matchedItem[$qKey] === $quantity) {
        $price = $matchedItem[$pKey];
        break;
    }
}

// 输出结果
echo "p1 = {$price}"; // 输出:p1 = 0.25

扩展说明

如果你的场景是阶梯计价(比如quantity=70时匹配q2=100的区间),可以将判断条件调整为:

if ($quantity <= (int)$matchedItem[$qKey]) {
    $price = $matchedItem[$pKey];
    break;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:42:50