我正在使用Alphavantange.co的API来获取股价。我需要遍历API提供的所有值。
我已经从api返回了JSON,并使用json_decode。 我可以得到1的值,例如,我可以得到63.3700使用以下代码回显到屏幕:
<?php
$string = file_get_contents("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=LLOY.l&outputsize=full&apikey=XXXX");
$arr = json_decode($string, true);
echo $arr['Time Series (Daily)']['2019-04-04']['1. open'].'<br>';
?>
api返回以下内容(前几条记录的示例)
{
"Meta Data": {
"1. Information": "Daily Time Series with Splits and Dividend Events",
"2. Symbol": "LLOY.l",
"3. Last Refreshed": "2019-04-05",
"4. Output Size": "Full size",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2019-04-05": {
"1. open": "62.4500",
"2. high": "62.9000",
"3. low": "62.0800",
"4. close": "62.2100",
"5. adjusted close": "62.2100",
"6. volume": "218007230",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0000"
},
"2019-04-04": {
"1. open": "63.3700",
"2. high": "63.3800",
"3. low": "62.3500",
"4. close": "62.6200",
"5. adjusted close": "62.6200",
"6. volume": "193406609",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0000"
},
"2019-04-03": {
"1. open": "64.1200",
"2. high": "65.5400",
"3. low": "63.9300",
"4. close": "64.8800",
"5. adjusted close": "62.7400",
"6. volume": "231702090",
"7. dividend amount": "0.0000",
"8. split coefficient": "1.0000"
我一次可以得到一个值,但最终需要遍历所有值以将它们写入MySQL表。当每个级别具有不同的“名称”(不同的日期)时,如何遍历它们?
作为第一个帮助,我将如何输出每个日期的Open值,例如 2019-04-05 62.4500 2019-04-04 63.3700 2019-04-03 64.1200
答案 0 :(得分:0)
您必须将JSON解码为数组,可以使用函数json_decode
将JSON转换为数组并在循环内应用逻辑
$responseToArray = json_decode($response, TRUE);//$response is JSON
现在您可以使用循环了
foreach($responseToArray as $key => $value){
/*
Your Code here, you can further do the
loop through $value ...and so on
*/
}
有关更多详细信息,请参见PHP manual。
答案 1 :(得分:0)
您可以遍历数组以访问其所有元素。由于数据的结构,您可能需要像这样的嵌套循环:
$arr = json_decode( $string, TRUE );
// check if the array key exists
if ( ! empty( $arr['Time Series (Daily)'] ) {
// loop over the contents of Time Series
foreach( $arr['Time Series (Daily)'] AS $date => $results ) {
// loop over the results for each date in Time Series
foreach( $results AS $key => $value ) {
echo '<br>For ' . $key . ' on ' . $date . ' the value is ' . $value;
}
}
}