1

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.

2
  • If you just want json, you should only use json_encode(), not serialize(). Commented Nov 22, 2017 at 6:51
  • but its giving me a empty result.[{}] @MagnusEriksson Commented Nov 22, 2017 at 6:51

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.