【问题标题】:How to decode a json from api in php (multidimensional array)如何在php(多维数组)中从api解码json
【发布时间】:2021-12-17 22:34:41
【问题描述】:

我想在wordpress中用php解码json代码。

这是我的代码。但没有用。

function decode_func(){
    $json = file_get_contents('https://api.pray.zone/v2/times/today.json?city=jakarta');
    $decoded_json = json_decode($json,true);
    $results = $decoded_json['results'];

    foreach($results as $result) {
        $datetime = $result['datetime'];
        foreach($datetime as $datetim) {
            $times = $datetim['times'];
            foreach($times as $time) {
                echo $time['Sunrise'];
            }
        }
    }
}

add_shortcode('decode','decode_func');

【问题讨论】:

  • “没用”是什么意思?你有错误吗?
  • @mrodo。什么都不能退货。输出为空!没有显示错误。
  • 您必须更具体。短代码运行了吗? "$times = datetim['times']" 有错别字,$datetime 中缺少最后一个 "e"。
  • $decoded_json 工作正常并返回一个有效的多维数组。您对其中的哪些数组感兴趣?
  • @Ruvee 时间和日期数组。

标签: php json wordpress


【解决方案1】:

我测试了您的代码,发现您的属性定位不正确。

要单独通过 foreach 循环而不是直接针对该属性获取 Sunrise 属性,您需要执行以下操作。

$json         = file_get_contents('https://api.pray.zone/v2/times/today.json?city=jakarta');
$decoded_json = json_decode($json,true);
$results      = $decoded_json['results'];

foreach ($results as $key => $result) {
    if ($key !== 'datetime') continue;

    foreach($result as $datetime) {
        foreach ($datetime as $time) {
            if (!empty($time['Sunrise'])) echo $time['Sunrise'];
        }
    }
}

编辑

为了同时获得城市,我用 elseif 创建了一个新的 if 条件。
代码几乎相同,因为位置不是一个多维数组,它获取城市值的次数较少

$json         = file_get_contents('https://api.pray.zone/v2/times/today.json?city=jakarta');
$decoded_json = json_decode($json,true);
$results      = $decoded_json['results'];

foreach ($results as $key => $result) {
    if ($key === 'datetime') {
        foreach($result as $datetime) {
            foreach ($datetime as $time) {
                if (!empty($time['Sunrise'])) echo $time['Sunrise'];
            }
        }
    } else if ($key === 'location') {
        if (!empty($result['city'])) echo $result['city'];
    }
}

【讨论】:

  • 非常感谢。工作正常。你能帮我如何在“位置”数组中获取“城市”名称吗?谢谢。
  • @Tadbi 更新了我的答案以包括城市
  • 谢谢'人。伟大的
猜你喜欢
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 2018-07-13
相关资源
最近更新 更多