我的班级实现了
php中的json序列化
然后我的类实现了 jsonSerialize 方法并返回 get_object_vars($this)。
public function JsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
Run Code Online (Sandbox Code Playgroud)
问题在于它也返回包括 NULL 变量在内的所有值。我怎样才能只获取非空变量作为 json 输出?
传递$vars给函数array_filter()。如果您不提供回调,它将删除与FALSE
public function JsonSerialize()
{
$vars = array_filter(get_object_vars($this));
return $vars;
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要删除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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
718 次 |
| 最近记录: |