从json回应多个变量

时间:2018-05-04 07:52:42

标签: json

$api_url='https://min-api.cryptocompare.com/data/price? 
fsym=BTC&tsyms=USD,EUR,AUD,GBP';

//{"USD":9662.45,"EUR":8049.92,"AUD":12792.38,"GBP":6998.2}

$cryptocurrency = json_decode(file_get_contents($api_url));

$priceUSD = (float) $cryptocurrency->USD;

$priceAUD = (float) $cryptocurrency->AUD;

$priceEUR = (float) $cryptocurrency->EUR;

$priceGBP = (float) $cryptocurrency->GBP;

 echo  'BTC<br>';
 echo  $priceUSD.'<br>';
 echo  $priceAUD.'<br>';
 echo  $priceEUR.'<br>';
 echo  $priceGBP.'<br>';

以上代码适用于变量 fsym = BTC

我需要用 fsyms = BTC,ETH,DASH 和echo作为下面的示例请求

$api_url='https://min-api.cryptocompare.com/data/pricemulti? 
fsyms=BTC,ETH,DASH&tsyms=USD,EUR,AUD,GBP';

//{"BTC":{"USD":9665.27,"EUR":8055.28,"AUD":12763.35,"GBP":6980.47},"ETH": 
{"USD":778.56,"EUR":648.67,"AUD":1030.77,"GBP":563.6},"DASH": 
{"USD":494.95,"EUR":410.57,"AUD":653.61,"GBP":357.47}}


$cryptocurrency = json_decode(file_get_contents($api_url));

$priceUSD = (float) $cryptocurrency->USD;

$priceAUD = (float) $cryptocurrency->AUD;

$priceEUR = (float) $cryptocurrency->EUR;

$priceGBP = (float) $cryptocurrency->GBP;

 echo  'BTC<br>';
 echo  $priceUSD.'<br>';
 echo  $priceAUD.'<br>';
 echo  $priceEUR.'<br>';
 echo  $priceGBP.'<br>';

 echo  'ETH<br>';
 echo  $priceUSD.'<br>';
 echo  $priceAUD.'<br>';
 echo  $priceEUR.'<br>';
 echo  $priceGBP.'<br>';

 echo  'DASH<br>';
 echo  $priceUSD.'<br>';
 echo  $priceAUD.'<br>';
 echo  $priceEUR.'<br>';
 echo  $priceGBP.'<br>';

我的代码不起作用,因为我尝试过的任何代码都没有成功。我假设我需要一些foreach代码,但无法解决如何实现。任何指导都将非常感激。谢谢

1 个答案:

答案 0 :(得分:0)

<?PHP

$api_url='https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH,DASH&tsyms=USD,EUR,AUD,GBP';


$cryptocurrency = json_decode(file_get_contents($api_url));


foreach($cryptocurrency as $key => $value)
{
$priceUSD = (float) $cryptocurrency->$key->USD;

$priceAUD = (float) $cryptocurrency->$key->AUD;

$priceEUR = (float) $cryptocurrency->$key->EUR;

$priceGBP = (float) $cryptocurrency->$key->GBP;

 echo  "$key<br>";
 echo  $priceUSD.'<br>';
 echo  $priceAUD.'<br>';
 echo  $priceEUR.'<br>';
 echo  $priceGBP.'<br>';

}
?>

请参阅http://php.net/manual/en/control-structures.foreach.php