我目前正在嘗試在一個變量中獲取我的 JSON 解碼輸出的每個標題這就是卷曲對我有用的東西$curl = curl_init();curl_setopt_array($curl, array( CURLOPT_URL => 'http://api.irail.be/disturbances/?format=json&lang=nl', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_HTTPHEADER => array( 'cache-control: no-cache', 'content-type: application/x-www-form-urlencoded' ),));$response = curl_exec($curl);$err = curl_error($curl);curl_close($curl);// Decode JSON response and get only the data needed:$response = json_decode($response);$response = $response->disturbance[0];var_dump($response);$name = $response->title;echo $name;當我刪除干擾后面的 [0] 時,我得到一個空白的 $name。有誰知道我該如何解決這個問題?
1 回答

MMMHUHU
TA貢獻1834條經驗 獲得超8個贊
您可以通過鍵訪問您的對象,但“干擾”不是鍵,而是鍵可以采用的值type。
您需要首先過濾數據以僅獲取帶有 的項目type = 'disturbance',然后才能獲取標題。
這是一個例子:
$response = json_decode($response);
$disturbanceItems = array_filter($response, function ($item){return $item->type == 'disturbance';});
echo $disturbanceItems[0]->title ;
- 1 回答
- 0 關注
- 80 瀏覽
添加回答
舉報
0/150
提交
取消