Phoebe
Phoebe

Reputation: 287

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();
    die;
}

$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"},
           {"source":"60","target":"mark","value":"80"}],
 "nodes": 
          [{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}

Any help is much appreciated. Thank you!

Upvotes: 0

Views: 54

Answers (1)

Halcyon
Halcyon

Reputation: 57719

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) { .. }

Upvotes: 3

Related Questions