我的类实现
php 中的jsonSerialize
然后,我的类实现jsonSerialize方法并返回get_object_vars($this)。
public function JsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
这样做的问题是它也会返回包括NULL变量在内的所有值。如何才能仅将非null变量作为json输出?
将$vars
传递给函数array_filter()
。如果你不给它提供回调,它将删除与FALSE
等效的所有内容
public function JsonSerialize()
{
$vars = array_filter(get_object_vars($this));
return $vars;
}
如果只需要删除NULL
属性并保留其他类似FALSE
的值(空字符串、零等),则需要编写一个函数来决定保留什么和删除什么:
public function JsonSerialize()
{
$vars = array_filter(
get_object_vars($this),
function ($item) {
// Keep only not-NULL values
return ! is_null($item);
}
);
return $vars;
}
只过滤$vars
vor空值:
<?php
public function JsonSerialize()
{
$vars = get_object_vars($this);
return array_filter($vars, function ($value) {
return null !== $value;
});
}