我正在嘗試了解如何在服務器之間傳輸數據。在線有一個包含 json 數據的測試 API。我嘗試了以下操作:- <?php// Initiate curl session in a variable (resource) $curl_handle = curl_init();$url = "http://dummy.restapiexample.com/api/v1/employees"; // website sample API data// Set the curl URL option curl_setopt($curl_handle, CURLOPT_URL, $url);// This option will return data as a string instead of direct output curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);// Execute curl & store data in a variable $curl_data = curl_exec($curl_handle);curl_close($curl_handle);// Write the JSON string// echo $curl_data; // the above writes the JSON string ok// Now try decoding to PHP array$character = json_decode($curl_data); echo $character[1]->employee_name; // this throws an error 'Error: Cannot use object of type stdClass as array in C:\wamp64\www\curlex\curlget.php on line 24' ?>返回的字符串包含以下內容(為清楚起見,已刪除為 2 個條目):- {"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""}]}我想 json_decode 由于{"status":"success","data":序言而失???請問如何解決?
3 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
你的問題是,你已經從函數中省略了第二個參數json_decode(),如果沒有設置,它將把字符串解析為一個對象,而不是一個數組。
您可以在此處找到此功能的文檔,在您的情況下,您正在尋找的是參數assoc。
另一方面,您顯示的示例返回employee_name在另一個屬性內查找的內容,而不是在主要屬性(即data)中。
true嘗試作為函數的第二個參數提供:
$character = json_decode($curl_data, true);
echo $character[1]['employee_name'];
但這只有在數據示例不準確的情況下才有效。如果該示例準確無誤,要獲取employee_name第二個數據元素的 ,請使用:
$character = json_decode($curl_data, true);
echo $character['data'][1]['employee_name'];
注意,php 數組是從零開始的,所以如果你想從數組中取出第一個元素,你應該引用它的第 0 個屬性。

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
您可以像這樣訪問它:
$character = json_decode($curl_data);
echo $character->data[1]->employee_name;
- 3 回答
- 0 關注
- 120 瀏覽
添加回答
舉報
0/150
提交
取消