how to use array_push for json_encode

可紊 提交于 2020-12-01 12:01:53

问题


I am iOS developer and I am making Webservices in PHP for getting JSON Response.

Code which I wrote is:

    $result = mysqli_query($con,"SELECT * FROM wp_marketcatagories");
    $data =array();
    while($row = mysqli_fetch_array($result))
                 {
                 $data[] = array_push($data, array('id' => $row['id']));
                 }
    $json = json_encode($data);
    echo $json;

This is what I want in result:

[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"},{"id":"7"},{"id":"8"},{"id":"9"},{"id":"10"},{"id":"11"},{"id":"12"}]

But above code is giving me like this:

[{"id":"1"},1,{"id":"2"},3,{"id":"3"},5,{"id":"4"},7,{"id":"5"},9,{"id":"6"},11,{"id":"7"},13,{"id":"8"},15,{"id":"9"},17,{"id":"10"},19,{"id":"11"},21,{"id":"12"},23]

From where this 1, 3, 5 ,.... are coming ?


回答1:


no need to assign it to $data[]. You are already pushing the values to the array $data

Just simply use

 array_push($data, array('id' => $row['id']));

instead of

 $data[] = array_push($data, array('id' => $row['id']));



回答2:


Array_Push(): Returns the new number of elements in the array.

...this is were your numbers are coming from and you're adding them to the array with your $data[] = statement

array_push($data, array('id' => $row['id']));

or

$data[] = array('id' => $row['id']);

Same result in this scenario




回答3:


You don't require to assign $data twice as you have written like this: $data[] = array_push($data, array('id' => $row['id']));

array_push — Push one or more elements onto the end of array syntax : array_push(array,value1,value2...)

Just write

array_push($data, array('id' => $row['id']));

or

$data[] = array('id' => $row['id']);


来源:https://stackoverflow.com/questions/22421132/how-to-use-array-push-for-json-encode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!