Put several query result in one JSON file using PHP

thomaszhwang
thomaszhwang used Ask the Experts™
on
I am using a PHP file to generate JSON files.  Now I have three queries.  I generate one JSON file for each of the queries.

I'm just wondering if it is possible to generate one JSON file for all three queries.

Following is the code I use to generate JSON files.  Thanks.

        $arr = array();
	$rs = mysql_query("
		SELECT
			Column
		FROM
			Table;
	");
	while($obj = mysql_fetch_object($rs)) {
		$arr[] = $obj;
	}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Wrap them into another array:

$json = json_encode(array($result1, $result2, $result3));

Open in new window

Author

Commented:
What's $result1 here?  Same as the $rs in my example?
Commented:
No. Since you have 3 queries, I assume that you have 3 $arr variables to store the results.
Then, your code would be like this:

        // Query #1
        $arr1 = array();
	$rs = mysql_query("
		SELECT
			Column
		FROM
			Table;
	");
	while($obj = mysql_fetch_object($rs)) {
		$arr1[] = $obj;
	}
        $arr2 = array();
	$rs = mysql_query("
		SELECT
			Column
		FROM
			Table;
	");
	while($obj = mysql_fetch_object($rs)) {
		$arr2[] = $obj;
	}
        $arr3 = array();
	$rs = mysql_query("
		SELECT
			Column
		FROM
			Table;
	");
	while($obj = mysql_fetch_object($rs)) {
		$arr3[] = $obj;
	}
	$json = json_encode(array($arr1, $arr2, $arr3));
        echo $json;

Open in new window

Author

Commented:
Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial