Getting the field of an object

58 views Asked by At

I have objects like below

{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

4

There are 4 answers

0
urfusion On BEST ANSWER

Use this code

$data = json_decode($data); //where $data contain the json
$data->user;
0
Karim On

It looks, like your objects are json-encoded. This means, you can use the native php functions json_encode() and json_decode() to process them. In your example, you can deserialize the object by calling

$obj = json_decode($str);

with $str being the data you show above. Now you can access the fields of this object with standard php access methods like

$type = $obj->type;

Hope this helps!

0
cn007b On

Don't forget to check errors after json_decode, like this:

$payload = json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Invalid JSON.');
}
// also you cah check this
if (property_exists($payload, 'user')) {
    var_export($payload->user);
}
0
kunal On

You can resolve with two ways :-

$data = '{
    "user": "58a9bf92e0f78000055dd932",
    "type": "template_created",
    "count": 2
    }';
$objectdata = json_decode($data); //stclassobject
echo $objectdata->count;
  --------OR-------
$arraydata= json_decode($data,true); //convert to array
echo $arraydata['count'];

Hope it hepls!