Garbit Garbit - 7 months ago 18
JSON Question

Check property exists - converting json to stdObject and then inserting value or null into db

I'm calling an API and handling a JSON response which is then decoded into a stdObject. Then I'm inserting the record into the db with either the value or NULL. However I'm finding my request doesn't always come back with a value


[1] => stdClass Object
[created_at] => Wed, 26 Oct 2011 09:58:47 +0000
[entities] => stdClass Object

[from_user] => powpowpow
[from_user_id] => 12345
[from_user_id_str] => 12345
[geo] =>
[location] => UK
[id] => 1245
[id_str] => 12345
[iso_language_code] => en
[metadata] => stdClass Object
[result_type] => recent

[profile_image_url] =>
[source] => <a href="">web</a>
[text] => some message!
[to_user_id] =>
[to_user_id_str] =>

What I've found is that some properties are not returned with every call, location, to_user_id and screen_name (which wasn't even returned in this call)

What i did was create a method;

function _nullify($var){
return $var = empty($var) ? NULL : $var;
} else {
return NULL;

This should have allowed me to check if the property exists and if it does if there is a value then return it otherwise return NULL so i can enter that into the db

However this method doesn't seem to work.

I hope you guys can help,

Many thanks,



As i see it, you're trying to check if a key exists in your object, You could use PHP's property_exists function for that.

function _nullify($object, $key){
    if(property_exists($object, $key))
        return empty($object->$key) ? NULL : $object->$key;
        return NULL;