Home > other >  How to decode a json from api in php (multidimensional array)
How to decode a json from api in php (multidimensional array)

Time:11-04

I want to decode json code with php in wordpress.

this is my code. but did not work.

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');

CodePudding user response:

I tested your code and what I found out is that your property targeting is incorrect.

In order to get the Sunrise property by foreach loops alone and not directly targeting that property you need to do the following.

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

EDIT

In order to get the city as well I created a new if condition with a elseif.
The code is almost the same, because location is not a multi dimentional array its less foreachs to get the city value

$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'];
    }
}
  • Related