【问题标题】:Getting a specific value from a json response从 json 响应中获取特定值
【发布时间】:2020-07-30 23:11:30
【问题描述】:

我有这个代码

$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 

【问题讨论】:

    标签: php laravel-7


    【解决方案1】:

    json_decode($variable),用于将 JSON 对象解码或转换为 PHP 对象。

    所以你可以这样做,因为$client['0'] 是一个对象。

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

    但我想说你应该将 json 对象转换为 关联数组 而不是 PHP 对象,方法是将 TRUE 作为参数传递给 json_decode。当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'];
    

    【讨论】:

    • 感谢您对更改内容的解释和示例
    • 嘿!我已经更新了解决方案。我已将$client['name'] 更改为$client[0]['name']。很抱歉我之前忘记添加了 :)
    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2019-08-26
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多