任何将剥离对象属性为null的PHP函数吗? [英] Any PHP function that will strip properties of an object that are null?
问题描述
我正在返回从ORM中提取的对象数组的json_encode().它包含许多具有空值的属性.删除这些为空的属性的最巧妙的方法是什么?我想我可以遍历这些属性,看看它们是否为null,然后对该属性进行unset(),但是肯定有一种更优雅的方法吗?
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?
推荐答案
尝试一下;它仅适用于简单对象,但如果它来自ORM,则应该足够简单.
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);
感谢 Gordon's 回答的另一个问题昨天是因为给了我这个主意.
Thanks to Gordon's answer to another question yesterday for giving me the idea.
这是
- 将对象转换为关联数组,其中对象属性是键,其值是数组值
- 使用带有默认参数的 array_filter 来删除具有错误(例如空或空)值的数组条目
- 将新数组转换回简单对象
- 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
请注意,这将删除所有具有空值的属性,包括空字符串,错误的布尔值和0,而不仅仅是空值;您可以更改array_filter调用,如果您想保留那些并且只远程那些完全为空的变量.
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);
});
这篇关于任何将剥离对象属性为null的PHP函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!