从 json 响应中获取特定值

我有这个代码


$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 


蝴蝶不菲
浏览 61回答 1
1回答

慕码人8056858

json_decode($variable),用于将 JSON 对象解码或转换为 PHP 对象。$client['0']所以你可以像对象一样这样做。echo $client['0']->name;但我想说你应该通过将 json_decode 作为参数传递来将 json 对象转换为关联数组而不是 PHP 对象。TRUE当 时TRUE,返回的对象被转换为关联数组。$client = json_decode($client, true);&nbsp;现在 $client 是Array(&nbsp; [0] => Array&nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; [id] => 1&nbsp; &nbsp; &nbsp; &nbsp; [name] => Jojohn@doe.com&nbsp; &nbsp; &nbsp; &nbsp; [email_verified_at] =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; [password] => $2y$10$pAvJ9/K7ZPOqw10WhfmToumK0TY1XihY8M9uAEEs4GkHZr4LdGc4e&nbsp; &nbsp; &nbsp; &nbsp; [remember_token] =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; [created_at] => 2020-07-29 21:08:02&nbsp; &nbsp; &nbsp; &nbsp; [updated_at] =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; [userid] => 2&nbsp; &nbsp; &nbsp; &nbsp; [account_rep] => 3&nbsp; &nbsp; ))现在你可以简单地做echo $client[0]['name'];
打开App,查看更多内容
随时随地看视频慕课网APP