其他目标添加到JSON恩$ C $光盘阵列 [英] Add Additional Objects to JSON Encoded Array
问题描述
我目前使用JSON EN $ C $光盘阵列,以显示我的数据库用户对于自动建议功能。
I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature.
这看起来是这样的:
$sth = mysql_query("SELECT id, name FROM users");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
print json_encode($data);
这将返回:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"}]
我的问题是有点2倍:
My question is somewhat 2-fold:
首页后,我将如何手动额外添加对象的输出?例如,假设我想补充: {ID:444,名:一个新的名字}
First, how would I manually add an additional object to this output? For example, let's say I wanted to add: {"id":"444","name":"A New Name"}
因此,它会是这样的:
Thus, it'd look like:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"},{"id":"444","name":"A New Name"}]
二,让我们说我也想更多的对象添加到从一个单独的表数组为好,如:
Second, let's say I also wanted to add more objects to the array from a separate table as well, such as:
$sth = mysql_query("SELECT id, title FROM another_table");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['title'];
$json['id'] = $row['id'];
$data[] = $json;
}
print json_encode($data);
这样我可以在两个表的JSON数组中的填充,因此显示为其他选项我自动提示。
This way I could have both tables populated in the JSON array, thus, showing up as additional options in my autosuggest.
希望这是有道理的,因为我已经努力尝试表达什么,我试图完成。
Hopefully this makes sense, as I've tried hard to articulate what I am trying to accomplish.
谢谢!
推荐答案
只要保持按向 $数据
阵列。
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
$data[] = $json;
}
$custom = array('name'=>'foo', 'id' => 'bar');
$data[] = $custom;
然后在最后,做你的 json_en code
。假设你不是指有多个ajax调用它合并了JS本身。
Then at the very end, do your json_encode
. Assuming you're not referring to merging it in the JS itself with multiple ajax calls.
如果你有单独的脚本,在一个PHP页面将它们结合起来。
And if you have separate scripts, combine them in one php page.
这篇关于其他目标添加到JSON恩$ C $光盘阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!