Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

oop - Any PHP function that will strip properties of an object that are null?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this; it will only work on a simple object, but if it's coming from an ORM it should be simple enough.

// Strips any false-y values
$object = (object) array_filter((array) $object);

Thanks to Gordon's answer to another question yesterday for giving me the idea.

This works by

  • converting the object to an associative array, where object properties are the keys and their values are the array values
  • using array_filter with default arguments to remove array entries with a false (e.g. empty, or null) values
  • converting the new array back to a simple object

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.

// Strips only null values
$object = (object) array_filter((array) $object, function ($val) {
    return !is_null($val);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...