如何从 php 中的 json 中获取字段密码的值
[
{
"rid":"#145:0",
"version":1,
"oClass":"Login",
"oData":{
"Password":"hacker007",
"role":null,
"Name":"Nijeesh Joshy",
"Email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46282f2c2323352e72272a2a06212b272f2a6825292b" rel="noreferrer noopener nofollow">[email protected]</a>"
}
}
]
这是我的代码
$json = '[
{
"rid":"#145:0",
"version":1,
"oClass":"Login",
"oData":{
"Password":"hacker007",
"role":null,
"Name":"Nijeesh Joshy",
"Email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="197770737c7c6a712d787575597e74787075377a7674" rel="noreferrer noopener nofollow">[email protected]</a>"
}
}
]';
$json = json_decode($json,true);
echo $json[0]->oData->Name;
我收到此错误
Notice: Trying to get property of non-object
最佳答案
我发现在 json_decode()
步骤之后,属性不再受到保护:
$json_data = '[
{
"rid":"#145:0",
"version":1,
"oClass":"Login",
"oData":{
"Password":"hacker007",
"role":null,
"Name":"Nijeesh Joshy",
"Email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="553b3c3f3030263d61343939153238343c397b363a38" rel="noreferrer noopener nofollow">[email protected]</a>"
}
}
]';
$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" }
注意:
用于构建原始数据数组的类必须为您提供以正确方式获取数据的方法。
关于php - 如何在 php 中从此 JSON 获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357460/