
本文详解如何在 php 中解析含嵌套数组的 json 数据,并根据 amount 和 measure 双条件快速检索 pack 中对应的 price 值,提供兼容性良好的函数式与循环式两种实现方案。
本文详解如何在 php 中解析含嵌套数组的 json 数据,并根据 amount 和 measure 双条件快速检索 pack 中对应的 price 值,提供兼容性良好的函数式与循环式两种实现方案。
在处理结构化 JSON 数据时,常需从对象数组(如 packs)中按多个字段(如 amount 和 measure)精准匹配并提取特定值(如 price)。以如下示例数据为例:
{
"code": "08261",
"currency": "EUR",
"packs": [
{"amount": 0.05, "measure": "g", "price": 73.0},
{"amount": 0.1, "measure": "g", "price": 108.0},
{"amount": 1.0, "measure": "g", "price": 394.0},
{"amount": 5.0, "measure": "g", "price": 1142.0},
{"amount": 10.0, "measure": "g", "price": 1693.0}
]
}推荐使用 关联数组解码方式(json_decode($json, true)),因其支持直观的键名访问与原生数组操作:
✅ 推荐方案:函数封装 + array_filter(PHP ≥ 5.3)
function get_price(array $data, float $amount, string $measure): float {
$matches = array_filter($data['packs'], function ($pack) use ($amount, $measure) {
return abs($pack['amount'] - $amount) < 1e-10 && $pack['measure'] === $measure;
});
return !empty($matches) ? reset($matches)['price'] : 0.0;
}
$json = '{"code":"08261","currency":"EUR","packs":[{"amount":0.05,"measure":"g","price":73.0},{"amount":0.1,"measure":"g","price":108.0},{"amount":1.0,"measure":"g","price":394.0},{"amount":5.0,"measure":"g","price":1142.0},{"amount":10.0,"measure":"g","price":1693.0}]}';
$parsed = json_decode($json, true);
echo get_price($parsed, 1.0, 'g') . "\n"; // 输出: 394
echo get_price($parsed, 5.0, 'g') . "\n"; // 输出: 1142
echo get_price($parsed, 10.0, 'g') . "\n"; // 输出: 1693⚠️ 注意:浮点数比较建议用误差容限(如
abs($a - $b) )替代严格 <code>==,避免精度问题。
? 兼容方案:传统 foreach 循环(适用于 PHP function get_price_fallback(array $data, float $amount, string $measure): float {
foreach ($data['packs'] as $pack) {
if (abs($pack['amount'] - $amount) < 1e-10 && $pack['measure'] === $measure) {
return (float)$pack['price'];
}
}
return 0.0;
}
该写法无匿名函数依赖,逻辑清晰、调试友好,且性能在中小规模数组中表现优异。
? 关键要点总结
- 始终优先使用
json_decode($json, true)将 JSON 转为关联数组,便于后续过滤与遍历; - 避免直接对浮点字段(如
amount)使用==判断,应采用容差比较; - 若需高频查询,可预先构建索引(如
[$amount.'_'.$measure] => $price的哈希表),提升 O(n) → O(1); - 错误处理建议:增加
json_last_error()检查,确保 JSON 解析成功;对缺失键使用??或isset()防御性访问。
通过以上方法,您可稳健、高效地从嵌套 JSON 数组中提取任意组合条件下的目标值。


















