php 如何将 array_push 用于 json_encode
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22421132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use array_push for json_encode
提问by Usama Sadiq
I am iOS developer and I am making Webservices in PHP for getting JSON Response.
我是 iOS 开发人员,我正在用 PHP 制作 Web 服务以获取 JSON 响应。
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, 3, 5 .... 从哪里来?
回答by anurupr
no need to assign it to $data[]. You are already pushing the values to the array $data
无需将其分配给$data[]. 您已经将值推送到数组$data
Just simply use
只需简单地使用
array_push($data, array('id' => $row['id']));
instead of
代替
$data[] = array_push($data, array('id' => $row['id']));
回答by Scuzzy
Array_Push(): Returns the new number of elements in the array.
Array_Push():返回数组中新的元素数。
...this is were your numbers are coming from and you're adding them to the array with your $data[] =statement
...这是你的数字来自,你用你的$data[] =语句将它们添加到数组中
array_push($data, array('id' => $row['id']));
or
或者
$data[] = array('id' => $row['id']);
Same result in this scenario
在这种情况下结果相同
回答by Nikunj Kabariya
You don't require to assign $data twice as you have written like this: $data[] = array_push($data, array('id' => $row['id']));
您不需要像这样编写 $data 两次分配 $data: $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...)
array_push — 将一个或多个元素推送到数组语法的末尾: array_push(array,value1,value2...)
Just write
写就好了
array_push($data, array('id' => $row['id']));
or
或者
$data[] = array('id' => $row['id']);

