Phoebe Phoebe - 9 months ago 70
JSON Question

MySQL to JSON - Combining Two Queries / Formatting

I am using PHP/MySQL to run a query and encode it as JSON, but I'm unsure how to get the JSON into the form that I need.

Here is my PHP:

$myquery1 = "select 'links' as type, source, target, value from table";

$myquery2 = "select 'nodes' as type, name from table2";

$query = mysql_query($myquery1);

if ( ! $query ) {
echo mysql_error();

$data = array();

for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);

//(and again for myquery2)

echo json_encode($data); //not sure how to combine queries here

I would like the JSON to be grouped grouped by "type," like this:

"links": [{"source":"58","target":"john","value":"95"},
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]

Any help is much appreciated. Thank you!

Answer Source

You can do:

$data = array(
    "links" => array(),
    "nodes" => array()
// for each link
$data["links"][] = mysql_fetch_assoc($query);
// for each node
$data["nodes"][] = mysql_fetch_assoc($query);

I think mysql_fetch_assoc adds each column twice, once by it's name and once by it's index so you will want to do some trimming. ie:

$row = mysql_fetch_assoc($query);
$data["links"][] = array(
    "name" => $row["name"],
    .. etc

Doing mysql_num_rows($query) in the for-loop condition might be a problem. The value never changes but PHP has to run the function every loop. Cache the value or use:

while (($row = mysql_fetch_assoc($res)) !== false) { .. }