Reputation:
I have no trouble at all outputting MySQL data to an array then encoding in json.
What I am trying to understand is how can I add to this json output other pieces of non-dynamic data.
if (mysql_num_rows($result) > 0) {
while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
echo $_GET['callback'].'('.json_encode($arr).')';
}else{
}
What I need for example is to add something like
"firstnumber":"0"
"secondnumber":"10"
Is there a way to successfully add this form of data with the array of results and encode it all?
Upvotes: 0
Views: 864
Reputation: 24549
I would create an array with my other data, and then append it to the end:
if (mysql_num_rows($result) > 0) {
while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
// Add other data
$otherData = Array('firstnumber'=>0, 'secondnumber'=>10);
// Append other data to end of array
$arr[] = $otherData;
echo $_GET['callback'].'('.json_encode($arr).')';
}else{
}
Upvotes: 0
Reputation: 360692
You can mix/match PHP arrays. The array you build with the database fetch loop will be given numeric keys (0, 1, 2, ...), and then you can add the 'firstnumber' and 'secondnumber' keys yourself afterwards.
however, this makes iterating the loop a bit tricky later, as you'll have to differentiate between the key types. However, nothing stops you from doing a nested structure:
$data = array();
while(...) {
$data['stuff_from_db'][] = $obj;
}
$data['other_stuff']['first_number'] = 0;
$data['other_stuff']['second_number'] = 10;
which allows you to keep the database results and the "other stuff" in parallel separate branches of the array.
Upvotes: 1