I am returning a json_encode() of an array of objects pulled from an ORM. It includes lots of properties with a null value. What is the neatest way to remove these properties that are null? I guess I could iterate over the properties, look if they are null and then unset() that property, but surely there must be a more elegant way?
相关问题
- Views base64 encoded blob in HTML with PHP
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- Laravel Option Select - Default Issue
- How to maintain order of key-value in DataFrame sa
There's no standard function to remove null-valued properties. Writing one of your own isn't inelegant, if you write one elegantly.
I made this function that solves my problem: clean null 'object properties' and 'array properties' inside an object. Also, you can have many 'levels' of objects/arrays inside of an object:
Despite the name you can also use
array_walk
with a closure:Output
Building off of @Gordon 's answer, a couple of adjustments would be needed to make that work, but you can also use array_walk_recursive instead. The reference is required or otherwise any changes you make to the object won't apply to the scope outside of the Closure.
IE:
Try this; it will only work on a simple object, but if it's coming from an ORM it should be simple enough.
Thanks to Gordon's answer to another question yesterday for giving me the idea.
This works by
Note that this will remove all properties with empty values, including empty strings, false boolean values and 0s, not just nulls; you can change the array_filter call if you want to keep those and only remote those that are exactly null.
I'm going to add to the response given by El Yobo because that will only work if you have a 1 dimensional object or array. If there is any array or object nesting then in order to get the accepted solution to work you must create some sort of recursive array filter. Not good.
The best solution my colleague and I came up with was to actually perform a regular expression on the JSON string before it was returned from the server.
The regular expression will remove all places in the string of the form
,"key":null
including any whitespace between the leading comma and the start of the key. It will also match "key":null, afterwards to make sure that no null values were found at the beginning of a JSON object.This obviously isn't the most ideal situation but it will effectively remove null entries without having to develop some kind of recursive array filter.