douliang4858 2013-04-28 02:54
浏览 23

如何将更多数据附加到从SQL查询创建的JSON编码数组?

I have a query that is sent to my SQL database from PHP. It looks something like this:

$result = mysql_query("SELECT ...");
while($r = mysql_fetch_assoc($result)) {
    $rows[] = $r;
}
print json_encode($rows);

I ultimately return the json_encoded result to my Java application (Android, actually) so that I can pick apart the pieces and put them into a nice Java object.

I have come to a point where I need some more data to come from this query, and I don't know how to get it. Is there a way for me to give myself the results of ANOTHER query, and inject it into this json_encoded result? Like basically run another query, and append it to the $r on each iteration of the loop and have it "seem" as if it was another column returned from the original queries select? I just don't know how to handle this $rows[] array.

Let me know if my question is not clear.

  • 写回答

1条回答 默认 最新

  • douyi2664 2013-04-28 02:56
    关注

    Add mutiple levels to your PHP array:

    $data = array();
    
    $data['part1'] = 'data from query 1';
    $data['part2'] = 'data from query 2';
    
    echo json_encode($data);
    

    then simply refer to those sub-arrays in your client-side code.

    评论

报告相同问题?