将其他对象添加到JSON编码阵列

时间:2010-08-17 15:42:51

标签: 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[] = $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中显示为其他选项。

希望这是有道理的,因为我已经尽力阐明我想要完成的事情。

谢谢!

4 个答案:

答案 0 :(得分:13)

继续推送到$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_encode。假设你没有提到在JS本身中将它与多个ajax调用合并。

如果您有单独的脚本,请将它们合并到一个php页面中。

答案 1 :(得分:4)

尝试这种方式: -

$temp = json_encode($json);  //$json={"var1":"value1","var2":"value2"}   
$temp=substr($temp,0,-1);
$temp.=',"variable":"'.$value.'"}';

答案 2 :(得分:1)

您可以编辑JSON(文本),但在编码之前修改数组要容易得多。 或者我错过了什么?

答案 3 :(得分:0)

我不是这些领域的专家,但我会试着看看能否提供帮助。尝试其中之一:

选项1(我不知道联盟在mysql中的工作方式):

$sth = mysql_query("SELECT id, name FROM users union SELECT id, name FROM (SELECT id, title as name from another_table) as T2"); 


    $json = array(); 

        while($row = mysql_fetch_assoc($sth)) { 
            $json['name'] = $row['name']; 
            $json['id'] = $row['id']; 
        }

    $json['name'] = 'A new name';
    $json['id'] = '444';
    $data[] = $json; 

    print json_encode($data);

我从未做过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);

希望这有帮助。

相关问题