Reputation: 4088
I am trying to convert a PHP array object to an JSON.Following is the PHP Array Object;
Array
(
[0] => Project\Man\Model\Branch Object
(
[id:protected] => 123456
[name:protected] => Parent Branch
[type:protected] => services
)
)
I tried Serializing it but its not in a friendly readable object.
I tried the following:
json_encode
serialize
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";}}[{}]
I am trying for some solution where i can get JSON. any help.
Upvotes: 1
Views: 1319
Reputation: 13635
If you just want json, you should only use json_encode(), not serialize().
Since your object properties are set as protected
, they will however not be available when you encode the object whitout some additional help.
This is where the interface JsonSerializable comes into play.
You need to make sure that the object you want to encode implements the interface. Then you need to add a jsonSerialize()
method to the class.
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,
];
}
}
If you now pass this object through json_encode()
and you'll get a json string with what our new method returns.
Upvotes: 2