[英]PHP Array Object to Serialize
我正在尝试将PHP数组对象转换为JSON。
Array
(
[0] => Project\Man\Model\Branch Object
(
[id:protected] => 123456
[name:protected] => Parent Branch
[type:protected] => services
)
)
我试着序列化它,但是它不在友好的可读对象中。
我尝试了以下方法:
json_encode
连载
a:1:{i:0;O:23:"Project\Man\Model\Branch ":3:{s:5:"*id";s:36:"123456";s:7:"*name";s:20:"Parent Branch";s:7:"*type";s:8:"services";}}[{}]
我正在尝试一些可以获取JSON的解决方案。 任何帮助。
如果只需要json,则应仅使用json_encode(),而不要使用serialize()。
由于您的对象属性设置为protected
,但是在对对象进行编码时,如果没有其他帮助,它们将不可用。
这是接口JsonSerializable起作用的地方。
您需要确保要编码的对象实现了接口。 然后,您需要向jsonSerialize()
添加jsonSerialize()
方法。
class Branch implements \JsonSerializable
{
protected $id;
protected $name;
protected $type;
// ... your class code
public function jsonSerialize()
{
// Return what you want to be encoded
return [
'id' => $this->id,
'name' => $this->name,
'type' => $this->type,
];
}
}
如果现在通过json_encode()
传递此对象,您将获得一个包含我们新方法返回内容的json字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.