繁体   English   中英

PHP循环遍历多级Alphavantage API JSON

[英]PHP looping through multilevel 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表。 当每个级别具有不同的“名称”(不同的日期)时,如何遍历它们?

作为第一个帮助,我如何输出每个日期的开放值,例如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手册

您可以遍历数组以访问其所有元素。 由于数据的结构,您可能需要一个嵌套循环,如下所示:

$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; 
        } 
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM