Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  55] [ 5]  / answers: 1 / hits: 32257  / 14 Years ago, tue, august 17, 2010, 12:00:00

I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature.



It looks something like this:



$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);


This returns:



[{id:81,name:John Doe},{id:82,name:Jane Doe}]


My question is somewhat 2-fold:



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);


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.



Thanks!


More From » php

 Answers
84

Just keep pushing to the $data array.



$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;


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.



And if you have separate scripts, combine them in one php page.


[#95888] Sunday, August 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arron

Total Points: 663
Total Questions: 119
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
;