【问题标题】:how to get elements from this JSON in php如何在 php 中从此 JSON 中获取元素
【发布时间】:2017-06-04 18:26:28
【问题描述】:

我如何从 php 中的这个 json 获取字段密码的值

[  
   {  
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{  
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"nijeesh4all@gmail.com"
      }
   }
]

这是我的代码

$json = '[  
   {  
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{  
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"nijeesh4all@gmail.com"
      }
   }
]';

$json = json_decode($json,true);

echo $json[0]->oData->Name;

我收到这个错误

注意:试图获取非对象的属性

【问题讨论】:

  • 对不起,不是 Json,而是 php 数组和对象。
  • 我已使用 json_encode() 将其转换为 json,之后我如何访问数据
  • 为什么不在编码前访问数据?您正在尝试从 JS 访问数据?
  • 我正在尝试从 php 访问数据
  • 查看我更新的答案,只需将 json_decode() 函数的第二个参数设置为 false 或将其保留为默认值。

标签: php json orientdb


【解决方案1】:

我看到在json_decode() 步骤之后,属性不再受保护:

$json_data = '[
    {
        "rid":"#145:0",
        "version":1,
        "oClass":"Login",
        "oData":{
            "Password":"hacker007",
            "role":null,
            "Name":"Nijeesh Joshy",
            "Email":"nijeesh4all@gmail.com"
        }
    }
]';

$data = json_decode($json_data);

所以,您可以通过这种方式访问​​数据:

$array['name'] = $data[0]->oData->Name;
$array['password'] = $data[0]->oData->Password;

var_dump($array);

输出:

array(2) { 
    ["password"]=> string(9) "hacker007" 
    ["name"]=> string(13) "Nijeesh Joshy" 
}

注意:

用于构建原始数据数组的类必须为您提供以正确方式获取数据的方法。

【讨论】:

  • 我收到一个错误通知:尝试在第 67 行的 C:\xampp\htdocs\net\functions.php 中获取非对象的属性这是我的代码 pastebin.com/2jNdmJam
  • 好的,@nijeeshjoshy 只是不要使用 json_decode() 函数的第二个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 2021-11-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多