我正在使用 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.45002019-04-04 63.37002019-04-03 64.1200<</p>
您可以遍历数组以访问其所有元素。 由于数据的结构,您可能需要一个嵌套循环,如下所示:
$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;
}
}
}
您必须将 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 手册。