Reputation: 169
I am trying to return multiple arrays in one JSON object and having some difficulty with the syntax. An Android app receives updates from multiple tables, that I wish to be returned in one response.
Currently, this is how I am encoding the various result sets:
$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));
The data is returned in this format:
[{"table1":[{...}]},{"table2":[{...}]},...]
In the Android code, I'd like to be able to parse it as a JSONObject, from which I can then retrieve each array by name instead of parsing it as a JSONArray and retrieving each sub array by position. The JSON response would look like this instead:
{{"table1":[{...}]},{"table2":[{...}]},...}
It seems all I need to do is wrap the results arrays in an object, instead of an array on the PHP side, but although I've managed to blindly cobble together enough PHP code to get this far, I can't seem to figure out that final step.
Upvotes: 3
Views: 7451
Reputation: 169
@Anonymous answer did the trick. Just to clarify, I had to clean up what I was doing previously, so instead of this:
$table1['table1'] =$stmt_table1->fetchAll(PDO::FETCH_ASSOC);
$table2['table2'] =$stmt_table2->fetchAll(PDO::FETCH_ASSOC);
...
$json=json_encode(array($table1, $table2, $table3, $table4, $table5, $table6));
I now have this:
$table1_results =$stmt_table1->fetchAll(PDO::FETCH_ASSOC);
$table2_results =$stmt_table2->fetchAll(PDO::FETCH_ASSOC);
...
$json=json_encode(array('table1' => $table1_results , 'table2' => $table2_results,...);
Upvotes: 0
Reputation: 12090
Your last example is not valid JSON, curly braces always mean object with keys; instead you're treating it as an array. If you want an object, then add keys to the array in PHP like so:
$json=json_encode(array('a' => $table1, 'b' => $table2, 'c' => $table3));
This would then yield
{"a":{"table1":[{...}]},"b":{"table2":[{...}]},...}
Which seems to be what you want.
Upvotes: 5