I have this code
$client = json_decode($client); echo "<pre>"; print_r($client);
which produces there
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
)
)
My question is how do I get the value of name and account_rep I tried
echo $client['0']['object']['name'];
but that does not work it just throws an error
Cannot use object of type stdClass as array
Advertisement
Answer
json_decode($variable), is used to decode or convert a JSON object to a PHP object.
So you could do this as $client['0'] is an 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. When TRUE, returned objects get converted into associative arrays.
$client = json_decode($client, true);
Now $client is
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
)
)
Now you could simply do
echo $client[0]['name'];