我想在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');
uj5u.com熱心網友回復:
我測驗了您的代碼,發現您的屬性定位不正確。
為了Sunrise僅通過 foreach 回圈獲取屬性而不是直接針對該屬性,您需要執行以下操作。
$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 條件。
代碼幾乎相同,因為 location 不是多維陣列,獲取城市值的 foreachs 較少
$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'];
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346588.html
標籤:php json WordPress的
上一篇:CSS-將邊框半徑應用于gif
