php - PHP循环通过多级Alphavantage API JSON
问题描述
我正在使用来自 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
解决方案
您必须将 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 手册。
推荐阅读
- c# - 根据类型实例化对象
- javascript - 使用 node.js 从 FTP 下载文件
- python - NamedTuples、Hashable 和 Python
- python - 如何确定要导入的内容,例如与 QTreeWidget.findItems 一起使用的 matchFlags?
- c# - 在另一个脚本中使用一个脚本 c# unity
- azure - How to Joins an Azure virtual machine into an AD Domain using Azure CLI
- python - 了解 numpy 轴
- python - x轴上下交点求根函数
- php - 如果找不到,我们如何使用 Apache 重定向到新的 HTML 静态内容并回退到旧的基于 CMS 的 PHP 版本?(nginx try_files)
- javascript - 如何在 VS Code 中选择和替换匹配的语法