php 关联数组到 Json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10890107/
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
Associative array to Json
提问by Nick
I would like to be able to generate a json output in the following format:
我希望能够生成以下格式的 json 输出:
{"a":{"ax":1,"abx":2},"b":{"bax":1,"bbx":2},"c":3,"d":4,"e":5}
Although I have found that the respective code is this:
虽然我发现各自的代码是这样的:
$arr = array('a' => array('ax' => 1, 'abx' => 2), 'b' => array('bax' => 1, 'bbx' => 2), 'c' => 3, 'd' => 4, 'e' => 5);
, I'm struggling to generate this output by using data from an sql query. I have tried array_push() and array_merge() and the closest I have managed to get is this:
,我正在努力通过使用来自 sql 查询的数据来生成此输出。我试过 array_push() 和 array_merge() ,我设法得到的最接近的是:
[{"a":{"ax":1,"abx":2}},{"b":{"bax":1,"bbx":2}}, ....]
Any ideas?
有任何想法吗?
回答by Mghost.friend
First you should query all your data from table and then move it to an array, after this,use json_encode($array)function.
首先,您应该从表中查询所有数据,然后将其移动到数组中,然后使用json_encode($array)函数。
Place your array inside the parameters.
将数组放在参数中。
Then output will bee in json form.
然后输出将以 json 形式输出。
$query="select * from employees";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$employee=$row['employee'];
$country=$row['country'];
$employees[] = array('employee'=> $employee,'country'=> $country);
}
echo $jsonformat=json_encode($employees);
回答by None
Load the data you want encoded into an array then use json_encode().
将您想要编码的数据加载到数组中,然后使用json_encode()。
json_encode($arr);

