如何只对json写一次解码?
$content = file_get_contents('http://www.xmlcharts.com/cache/precious-metals.php?format=json');
$json = ($content);
foreach (json_decode($content, true) as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if($currency == "usd" and $commodity =="gold")
{
$gold_price = round($price, 2);
}
}
}
foreach (json_decode($content, true) as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if($currency == "usd" and $commodity =="silver")
{
$silver_price = round($price, 2);
}
}
}
foreach (json_decode($content, true) as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if($currency == "usd" and $commodity =="platinum")
{
$platinum_price = round($price, 2);
}
}
}
答案 0 :(得分:0)
将解码移动到var ...
$decodedContent = json_decode($content, true);
foreach ($decodedContent as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if($currency == "usd" and $commodity =="gold")
{
$gold_price = round($price, 2);
}
}
}
此外,您应该避免通过在foreach
中按$ commodity切换来进行三重循环 if($currency == "usd")
{
switch($commodity){
case 'gold':
$gold_price = round($price, 2);
break;
case 'silver':
$silver_price = round($price, 2);
break;
case 'platinum':
$platinum_price = round($price, 2);
break;
}
}
答案 1 :(得分:0)
怎么样:
foreach (json_decode($content, true) as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if($currency == "usd") and )
{
if($commodity =="gold"){
$gold_price = round($price, 2);
} elseif($commodity =="platinum"){
$platinum_price = round($price, 2);
} elseif($commodity =="silver"){
$silver_price = round($price, 2);
}
}
}
}
这样你就可以循环使用它了。
答案 2 :(得分:0)
如果你把金,银和铂金放在像$target_commodities
这样的数组中,这可能会更好,但这样做会让你只需要循环使用JSON一次
$decoded_json = json_decode($content, true)
$commodity_prices = array(
'gold' => 0,
'silver' => 0,
'platinum' => 0,
);
foreach ($decoded_json as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if ($currency == 'usd') {
switch ($commodity) {
case 'gold':
case 'silver':
case 'platinum':
$commodity_prices[$commodity] = round($price, 2);
break;
}
}
}
}
echo('Gold price: ' . $commodity_prices['gold']);
echo('Silver price: ' . $commodity_prices['silver']);
echo('Platinum price: ' . $commodity_prices['platinum']);
答案 3 :(得分:0)
以下是代码的简化版本(精简版),json_decode一次,没有额外的if / foreach循环。
$content = file_get_contents('http://www.xmlcharts.com/cache/precious-metals.php?format=json');
// Decode contents
$json = json_decode($content, true);
if(json_last_error() === JSON_ERROR_NONE) {
// Define defaults for variables
$gold_price = '';
$silver_price = '';
$platinum_price = '';
foreach ($json as $currency => $arr) {
foreach ($arr as $commodity => $price) {
if($currency == "usd") {
switch($commodity) {
case "gold":
$gold_price = money_format('%i', $price);
break;
case "silver":
$silver_price = money_format('%i', $price);
break;
case "platinum":
$platinum_price = money_format('%i', $price);
break;
}
}
}
}
} else {
echo 'Invalid JSON';
exit(0);
}