我有一個 cURL 檔案,它將回傳一個如下所示的陣列,我想知道如何宣告 [data]=>[id] 的變數。我嘗試了 $decoded.data 或 $decoded.[data] 但它不起作用.
Array
(
[data] => Array
(
[id] => 2
[email] => [email protected]
[first_name] => Janet
[last_name] => Weaver
[avatar] => https://reqres.in/img/faces/2-image.jpg
)
[support] => Array
(
[url] => https://reqres.in/#support-heading
[text] => To keep ReqRes free, contributions towards server costs are appreciated!
)
)
PHP 檔案:
<?php
$ch = curl_init();
$url = "https://reqres.in/api/users/2";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$decoded = json_decode($resp,true);
print_r($decoded);
curl_close($ch);
?>
uj5u.com熱心網友回復:
$decoded['data']
$decoded['data']['id']
是語法。但是端點必須回傳您使用 json_encode() 列印的陣列
uj5u.com熱心網友回復:
我有一個 cURL 檔案,它將回傳一個如下所示的陣列
讓我們分解您在這里要說的內容,并使用更清晰的術語來幫助您了解正在發生的事情。
$ch = curl_init();
$url = "https://reqres.in/api/users/2";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
curl_close($ch); // you can call this straight away, you're done with $ch
這使用一個名為“curl”的庫來發出 HTTP 請求,并獲取回應正文。in 的值$resp是一個字串——不是一個檔案,也不是任何 curl 甚至 HTTP 特定的東西,只是一個字串。
$decoded = json_decode($resp,true);
這需要字串,并根據稱為 JSON 的格式對其進行決議。將第二個引數設定為true表示您需要 PHP 陣列,而不是陣列和stdClass物件的混合。假設沒有錯誤,$decoded現在是一個陣列;不是 JSON 陣列,只是一個普通的 PHP 陣列。
print_r($decoded);
這就是您在問題中提出的輸出。重要的是要理解這不是“陣列”,它只是一種展示方式。其他方式包括var_dump($decoded);和var_export($decoded);。
所以,讓我們改寫你的第一句話:
我有一個 PHP 陣列,當使用
print_r. (它基于我使用 curl 獲取的 JSON 回應,但現在并不真正相關。)
現在,關于你的問題:
如何宣告 [data]=>[id] 的變數?
我認為您要說的是如何檢索“[data]=>[id]”中顯示的值。(相信我,了解正確的術語將使您在將來搜索和尋求幫助時更輕松。)
答案很簡單:在 PHP 中,使用語法訪問陣列元素$array['key']。所以$decoded['data']訪問輸出中顯示的所有[data] =>內容print_r,并$decoded['data']['id']訪問其中的內容[id] =>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448102.html
