在php中创建没有方括号[]的json响应

时间:2017-04-14 05:51:31

标签: php json

我正在尝试将json响应发送为:

num_zero = input('Enter number of zeros you want in a list:')
zero_list = [0 for i in range(num_zero)]
indices = raw_input('Enter the indices you want to convert separated by space:')
index_list = map(int, indices.split())
for i in index_list:
    zero_list[i] = 1

但是webservice正在生成json:

<p HighlightDirective [appHighlight]="inputtedColor">text to highlight</p>

以下是我的网络服务:

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

但是在json_encode下面会产生valide响应:

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

输出:

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

1 个答案:

答案 0 :(得分:2)

toArray()会转换Object中的Array。因此,您不需要在结果中添加toArray()

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

希望以上可行,如果没有,请尝试下面的代码,

$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;