aydinugur
aydinugur

Reputation: 1209

Getting the field of an object

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.

Upvotes: 0

Views: 62

Answers (4)

kunal
kunal

Reputation: 4248

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!

Upvotes: 0

cn0047
cn0047

Reputation: 17071

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);
}

Upvotes: 1

urfusion
urfusion

Reputation: 5501

Use this code

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

Upvotes: 1

Karim
Karim

Reputation: 361

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!

Upvotes: 1

Related Questions