我有以下json:
$data = '{"code":"08261",
"currency":"EUR",
"packs":[ {"amount":0.05,"measure":"g","price":73.0},
{"amount":0.1,"measure":"g","price":108.0},
{"amount":0.25,"measure":"g","price":154.0},
{"amount":0.5,"measure":"g","price":296.0},
{"amount":1.0,"measure":"g","price":394.0},
{"amount":2.5,"measure":"g","price":771.0},
{"amount":5.0,"measure":"g","price":1142.0},
{"amount":10.0,"measure":"g","price":1693.0}]}';
我可以得到代碼和貨幣的價值如下:
// Option 1: through the use of an array.
$jsonArray = json_decode($data,true);
$code = $jsonArray['code'];
// Option 2: through the use of an object.
$jsonObj = json_decode($data);
$code = $jsonObj->code;
我怎樣才能得到以下包的價格:
- 金額為“1.0”,度量為“g”
- 金額為“5.0”,度量為“g”
- 金額為“10.0”,度量為“g”
uj5u.com熱心網友回復:
如果將 json 轉換為嵌套陣列(傳遞true給 的$associative引數json_decode,則可以使用array_filter過濾包以查找所需的值:
$data = '{"code":"08261",
"currency":"EUR",
"packs":[ {"amount":0.05,"measure":"g","price":73.0},
{"amount":0.1,"measure":"g","price":108.0},
{"amount":0.25,"measure":"g","price":154.0},
{"amount":0.5,"measure":"g","price":296.0},
{"amount":1.0,"measure":"g","price":394.0},
{"amount":2.5,"measure":"g","price":771.0},
{"amount":5.0,"measure":"g","price":1142.0},
{"amount":10.0,"measure":"g","price":1693.0}]}';
function get_price($data, $amount, $measure) {
$values = array_filter($data['packs'], function ($a) use ($measure, $amount) {
return $a['amount'] == $amount && $a['measure'] == $measure;
});
if (count($values)) return reset($values)['price'];
return 0;
}
$data = json_decode($data, true);
echo get_price($data, 1.0, 'g') . PHP_EOL;
echo get_price($data, 5.0, 'g') . PHP_EOL;
echo get_price($data, 10.0, 'g') . PHP_EOL;
輸出:
394
1142
1693
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/505800.html
