Gagzzz
Gagzzz

Reputation: 142

create json response without brackets [] in php

I am trying to send json response as :

{"id":13,"user_id":4,"play_list_name":"My Play List12","section":1,"created":"2017-04-14T05:46:47+00:00","status":1}

but the webservice is generating json as:

[{"id":13,"user_id":4,"play_list_name":"My Play List12","section":1,"created":"2017-04-14T05:46:47+00:00","status":1}]

Below is my web service:

$response_data=$this->MyPlaylists->findById($id)->toArray();
echo json_encode($response_data); die;

However below json_encode is generating valide response:

     $response_data=array('response'=>0,'message'=>'This is already added in db');  
echo json_encode($response_data); die;

Output:

{"response":"already added","message":"This is already added in db"}

Upvotes: 0

Views: 437

Answers (1)

Rohan Kumar
Rohan Kumar

Reputation: 40639

toArray() will convert your Object in Array. So you don't need to add toArray() in your result.

$response_data=$this->MyPlaylists->findById($id);// without toArray()
echo json_encode($response_data); die;

Hope above will work and if not, then try the below code,

$response_data=$this->MyPlaylists->findById($id)->toArray();
echo json_encode(
     isset($response_data[0]->id)?
            $response_data[0]:
            array('response'=>0,'message'=>'This is already added in db')

);die;

Upvotes: 2

Related Questions