簡體   English   中英

從 json 響應中獲取特定值

[英]Getting a specific value from a json response

我有這個代碼

$client = json_decode($client); 
echo "<pre>";
print_r($client);

在那里生產

Array
(
  [0] => stdClass Object
    (
        [id] => 1
        [name] => Jojohn@doe.com
        [email_verified_at] => 
        [password] => $2y$10$pAvJ9/K7ZPOqw10WhfmToumK0TY1XihY8M9uAEEs4GkHZr4LdGc4e
        [remember_token] => 
        [created_at] => 2020-07-29 21:08:02
        [updated_at] => 
        [userid] => 2
        [account_rep] => 3
    )

)

我的問題是如何獲得我嘗試過的 name 和 account_rep 的值

echo $client['0']['object']['name'];

但這不起作用它只會引發錯誤

Cannot use object of type stdClass as array 

json_decode($variable),用於將 JSON object 解碼或轉換為 PHP ZA8ZCFDE6331BD59EB8661C

所以你可以這樣做,因為$client['0']是 object。

echo $client['0']->name;

But I'd say you should rather convert the json object to associative array instead of PHP object by passing TRUE to as an argument to the json_decode. TRUE時,返回的對象被轉換為關聯的 arrays。

$client = json_decode($client, true); 

現在 $client 是

Array
(
  [0] => Array
    (
        [id] => 1
        [name] => Jojohn@doe.com
        [email_verified_at] => 
        [password] => $2y$10$pAvJ9/K7ZPOqw10WhfmToumK0TY1XihY8M9uAEEs4GkHZr4LdGc4e
        [remember_token] => 
        [created_at] => 2020-07-29 21:08:02
        [updated_at] => 
        [userid] => 2
        [account_rep] => 3
    )

)

現在你可以簡單地做

echo $client[0]['name'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM