简体   繁体   中英

how to read values from nested json with php?

My cookie's value is JSON format string like this

{
    "_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 "{"

Here is PHP code

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

but if I do echo($_COOKIE['remember_me']) I get as result this`

{"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 ?

You can use json_decode to convert a JSON string to an array.

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. You need to convert it to an array using json_decode.

you need to decode the json

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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