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

PHP中如何从JSON的packs数组获取指定条件的price值?

获取指定条件的pack价格值

基于你提供的JSON数据和解析方式,以下是获取满足条件的pack对应price值的具体实现:

方法一:关联数组解析方式

先将JSON解析为关联数组,再通过遍历或过滤找到符合条件的项:

// 解析JSON为关联数组
$jsonArray = json_decode($data, true);

// 方式1:批量获取三个条件的价格
$targetConditions = [
    ['amount' => 1.0, 'measure' => 'g'],
    ['amount' => 5.0, 'measure' => 'g'],
    ['amount' => 10.0, 'measure' => 'g']
];

$matchedPrices = [];
foreach ($jsonArray['packs'] as $pack) {
    foreach ($targetConditions as $condition) {
        if ($pack['amount'] == $condition['amount'] && $pack['measure'] == $condition['measure']) {
            $matchedPrices[] = $pack['price'];
            break;
        }
    }
}
// 输出结果:Array ( [0] => 394.0 [1] => 1142.0 [2] => 1693.0 )
print_r($matchedPrices);

// 方式2:单独获取单个条件的价格(以amount=1.0为例)
$price1g = null;
foreach ($jsonArray['packs'] as $pack) {
    if ($pack['amount'] == 1.0 && $pack['measure'] == 'g') {
        $price1g = $pack['price'];
        break; // 找到后立即终止循环,提升效率
    }
}
echo $price1g; // 输出:394.0

方法二:对象解析方式

将JSON解析为对象后,通过对象属性访问来筛选:

// 解析JSON为对象
$jsonObj = json_decode($data);

// 批量获取三个条件的价格
$targetConditions = [
    ['amount' => 1.0, 'measure' => 'g'],
    ['amount' => 5.0, 'measure' => 'g'],
    ['amount' => 10.0, 'measure' => 'g']
];

$matchedPrices = [];
foreach ($jsonObj->packs as $pack) {
    foreach ($targetConditions as $condition) {
        if ($pack->amount == $condition['amount'] && $pack->measure == $condition['measure']) {
            $matchedPrices[] = $pack->price;
            break;
        }
    }
}
// 输出结果:Array ( [0] => 394.0 [1] => 1142.0 [2] => 1693.0 )
print_r($matchedPrices);

// 单独获取单个条件的价格(以amount=5.0为例)
$price5g = null;
foreach ($jsonObj->packs as $pack) {
    if ($pack->amount == 5.0 && $pack->measure == 'g') {
        $price5g = $pack->price;
        break;
    }
}
echo $price5g; // 输出:1142.0

数组方式的简洁写法(利用array_filter)

如果追求代码简洁,可以用array_filter快速过滤符合条件的项:

$jsonArray = json_decode($data, true);

// 获取amount=1.0且measure=g的价格
$filteredPack = array_filter($jsonArray['packs'], function($pack) {
    return $pack['amount'] == 1.0 && $pack['measure'] == 'g';
});
$price1g = reset($filteredPack)['price'];

// 获取amount=5.0且measure=g的价格
$filteredPack = array_filter($jsonArray['packs'], function($pack) {
    return $pack['amount'] == 5.0 && $pack['measure'] == 'g';
});
$price5g = reset($filteredPack)['price'];

// 获取amount=10.0且measure=g的价格
$filteredPack = array_filter($jsonArray['packs'], function($pack) {
    return $pack['amount'] == 10.0 && $pack['measure'] == 'g';
});
$price10g = reset($filteredPack)['price'];

echo "1.0g价格:{$price1g},5.0g价格:{$price5g},10.0g价格:{$price10g}";
// 输出:1.0g价格:394.0,5.0g价格:1142.0,10.0g价格:1693.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:15:41