简体   繁体   English

如何使用php从嵌套json中读取值?

[英]how to read values from nested json with php?

My cookie's value is JSON format string like this 我的cookie的值是这样的JSON格式字符串

{
    "_id":{
        "$oid":"5347d81c3e9b2ace058b4567"
    },
    "employee_id":{
        "$oid":"534ae3933e9b2a8f058b4568"
    },
    // some more data
} // it's from mongolab

In my PHP code when trying to get employee_id as result I get only "{" 在我的PHP代码中,尝试获取employee_id ,仅得到“ {”

Here is PHP code 这是PHP代码

if(isset($_COOKIE['remember_me'])){
    echo($_COOKIE['remember_me']['employee_id']);
}

but if I do echo($_COOKIE['remember_me']) I get as result this` 但是如果我做echo($_COOKIE['remember_me'])我得到的结果是echo($_COOKIE['remember_me'])

{"employee_id":{"$id":"5347d81c3e9b2ace058b4567"},"serial_number":"po9TsUdAK6nO6yFdSRyGcpSH7mqU6m+G","cookie_code":"YvfnP6\/PdDG8xhZRkEky1lKvS4n+AUom","hostname":"Titus","user_agent":"Mozilla\/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) Gecko\/20100101 Firefox\/28.0","user_ip":"127.0.0.1","last_used":false,"_id":{"$id":"534ae3933e9b2a8f058b4568"}} 

so I do something wrong, but I'm not experienced enough to find my mistake. 所以我做错了事,但是我没有足够的经验来发现自己的错误。 Please help, how get employee_id ? 请帮忙,如何获得employee_id

You can use json_decode to convert a JSON string to an array. 您可以使用json_decode将JSON字符串转换为数组。

In your case: 在您的情况下:

$rememberMe = json_decode($_COOKIE['remember_me'], true); // When the second parameter is true, json_decode will return an associative array.
$employeeId = $rememberMe['employee_id']['$id'];

In other words, right now the cookie is just a string. 换句话说,现在cookie只是一个字符串。 You need to convert it to an array using json_decode. 您需要使用json_decode将其转换为数组。

you need to decode the json 您需要解码json

$obj = json_decode($_COOKIE['remember_me']);
print $obj->{'employee_id'}; 

http://www.php.net/manual/en/function.json-decode.php http://www.php.net/manual/zh/function.json-decode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM