【问题标题】:How do I extract values from a multidimensional array using PHP如何使用 PHP 从多维数组中提取值
【发布时间】:2021-05-25 10:57:53
【问题描述】:

我正在使用 Alpha Vantage API 获取股票价格,并且能够轻松获取最新价格。但是我想从五个条目中取回价格。

这是我正在使用的数组的开始

{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2021-02-22",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2021-02-22": {
            "1. open": "118.5000",
            "2. high": "121.1250",
            "3. low": "118.4400",
            "4. close": "120.8600",
            "5. volume": "5838841"
        },
        "2021-02-19": {
            "1. open": "120.7500",
            "2. high": "120.7600",
            "3. low": "118.3800",
            "4. close": "118.9900",
            "5. volume": "6578741"
        },
        

这是我一直在使用的笨拙代码,

第一天,

把它变成时间,

请假 7 天(因为他们的交易所在周末关闭)并使用修改后的日期。

$getstocksapi = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=".$stock[$x]."&outputsize=compact&apikey=mycode;
$currentprices = file_get_contents($getstocksapi);
$currentprices = json_decode($currentprices,true);
$dateToCheck =($currentprices['Meta Data']['3. Last Refreshed']);
$oldDateToCheck = strtotime($dateToCheck);
$oldDateToCheck = ($oldDateToCheck  - 60 * 60 * 24 * 7);
$oldDateToCheck  = date("Y-m-d", $oldDateToCheck);
$dayEnd[$x] = ($currentprices['Time Series (Daily)'][$dateToCheck]['4. close']);
$thenDayEnd[$x] = ($currentprices['Time Series (Daily)'][$oldDateToCheck]['4. close']);

有没有更优雅的方法,也许使用 array_slice 可以获得最近的收盘价,然后是五个条目中的一个?

【问题讨论】:

  • “时间序列(每日)”不是已经按降序排列了吗?那么你只需要获取前五个元素
  • 谢谢。是的,它们是有序的。有什么想法可以简单地选择第五个吗?
  • 是的,第五个的索引为 4,因此您可以使用索引 $currentprices['Time Series (Daily)'][4]['4.关闭']
  • $dateToCheck =($currentprices['Meta Data']['3. Last Refreshed']); $prevFithDay = date('Y-m-d', strtotime('-5 days', strtotime($dateToCheck))); echo $currentprices['Time Series (Daily)'][$prevFithDay]['4. close'];
  • @AlivetoDie 我认为 op 是指第 5 个条目,而不是过去 5 天?

标签: php arrays api


【解决方案1】:

从评论中,数字索引不起作用,因为它仍然没有数字索引。要重新索引,您可以使用函数array_values()

$currentprices = json_decode($data, true);
$timeSeriesDaily = array_values($currentprices['Time Series (Daily)']);

那么$timeSeriesDaily 将是同一个数组,但带有数字索引,您可以使用以下内容访问第 5 个索引。

echo $timeSeriesDaily[4]['4. close'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多