
本文详解如何在 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)
abs($a - $b) )替代严格 ==,避免精度问题。











