我有这个代码
$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
答案 0 :(得分:1)
json_decode($ variable),用于将JSON对象解码或转换为PHP对象。
因此您可以这样做,因为$client['0']
是一个对象。
echo $client['0']->name;
但是我想说您应该通过将TRUE
作为参数传递给json_decode,而不是将JSON对象转换为关联数组。当TRUE
时,返回的对象将转换为关联数组。
$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'];