Php 向JSON编码的数组添加其他对象
我目前正在使用JSON编码的数组来显示数据库中的用户,以实现自动建议功能 它看起来像这样:Php 向JSON编码的数组添加其他对象,php,javascript,arrays,json,Php,Javascript,Arrays,Json,我目前正在使用JSON编码的数组来显示数据库中的用户,以实现自动建议功能 它看起来像这样: $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[] = $
$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"}]
我的问题有两个方面:
首先,如何手动向该输出中添加其他对象?例如,假设我想添加:{“id”:“444”,“name”:“A New name”}
因此,它看起来像:
[{"id":"81","name":"John Doe"},{"id":"82","name":"Jane Doe"},{"id":"444","name":"A New Name"}]
其次,假设我还想从单独的表向数组添加更多对象,例如:
$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数组中填充这两个表,从而在autosuggest中显示为附加选项
希望这是有意义的,因为我一直在努力阐明我要实现的目标
谢谢 您可以编辑JSON(文本),但是在编码之前修改数组要容易得多。
还是我遗漏了什么?只要继续按
$data
数组
$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\u编码
。假设您不是指将它与多个ajax调用合并到JS中
如果您有单独的脚本,请将它们合并到一个php页面中。我不是这些领域的专家,但我会尝试看看是否能提供帮助。请尝试以下方法之一: 选项1(我不知道联合在mysql中是如何工作的): 我从来没有做过PHP,所以我在做假设。我也从未使用过MySql,所以有更多的假设 备选案文2:
$sth = mysql_query("SELECT id, name FROM users");
$json = array();
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['name'];
$json['id'] = $row['id'];
}
$sth = mysql_query("SELECT id, title from another_table");
while($row = mysql_fetch_assoc($sth)) {
$json['name'] = $row['title'];
$json['id'] = $row['id'];
}
$json['name'] = 'A new name';
$json['id'] = '444';
$data[] = $json;
print json_encode($data);
希望这有帮助。尝试以下方法:-
$temp = json_encode($json); //$json={"var1":"value1","var2":"value2"}
$temp=substr($temp,0,-1);
$temp.=',"variable":"'.$value.'"}';
在进行json_编码之前,为什么不将它们添加到数组中?那对我来说更有意义。谢谢你,梅德。比我想象的要容易。
$temp = json_encode($json); //$json={"var1":"value1","var2":"value2"}
$temp=substr($temp,0,-1);
$temp.=',"variable":"'.$value.'"}';