のは、我々は、ネストされたオブジェクトをシリアル化する単純なオブジェクトがあるとしましょう:JsonSerializable :: jsonSerialize()でnullプロパティを無視する方法は?
class User implements \JsonSerializable
{
private $name;
private $email;
private $address;
public function jsonSerialize()
{
return [
'name' => $this->name,
'email' => $this->email,
'address' => $this->address
];
}
}
ネストされたオブジェクト:
class Address implements \JsonSerializable
{
private $city;
private $state;
public function jsonSerialize()
{
return [
'city' => $this->city,
'state' => $this->state
];
}
}
我々はシリアル化するためにjson_encode()
を使用し、これはネイティブJsonSerializable::jsonSerialize()を使用します。
$json = json_encode($user);
$name
と$state
がnullの場合、これを取得する方法:
{
"email": "[email protected]",
{
"city": "Paris"
}
}
の代わりに、この:
{
"name": null,
"email": "[email protected]",
{
"city": "Paris",
"state": null
}
}
自動的に行う方法はありません。シリアル化されているデータを調べ、すべてのヌル値をunset()する必要があります。それが再帰的であれば、何かarray_walkを使うことができます – Johnny
再帰を管理する例を挙げられますか? – Kwadz
以下の回答を参照 – Johnny