jangeador jangeador - 6 months ago 20
MySQL Question

mysql to json using php. Nested objects

Good Afternoon,
I am trying to get these results into arrays in PHP so that I can encode them into json objects and send them to the client. The results of the query look like this:

id name hours cat status
3bf JFK Int 24 pass open
3bf JFK Int 24 std closed
3bf JFK Int 24 exp open
5t6 Ohm CA 18 pass closed
5t6 Ohm CA 18 std closed
5t6 Ohm CA 18 std2 open
5t6 Ohm CA 18 exp open
...


I would like for the json objects to look like this:

{ "id": "3bf", "name": "JFK Int", "cats":
{ [ { "cat": "pass", "status": "open" },
{ "cat": "std", "status": "closed" },
{ "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
{ [ { "cat": "pass", "status": "closed" },
{ "cat": "std", "status": "closed" },
{ "cat": "std2", "status": "open" } ],
{ "cat": "exp", "status": "open" } ] }


I have succesfully connected to mysql and exported using json_encode using flat tables but this part I do not know how to do in PHP. Thanks.

This is the code that I have. This returns an array of json objects but it is flat, not nested:

$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";

$result = mysql_query($SQL);

$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = $row;}

$json = json_encode($arr);

echo $json;


The data itself is from a view that combines the tables ports and cats.

Answer

what you could do (sorry, not the best code I could write... short on time, ideas, and energy ;-) is something like this (I hope it still conveys the point):

$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";

$result = mysql_query($SQL);

$arr = array();
    while ($row = mysql_fetch_assoc($result)) {

        // You're going to overwrite these at each iteration, but who cares ;-)
        $arr[$row['id']]['id'] = $row['id'];
        $arr[$row['id']]['name'] = $row['name'];

        // You add the new category
        $temp = array('cat' => $row['cat'], 'status' => $row['status']);

        // New cat is ADDED
        $arr[$row['id']]['cats'][] = $temp;
    }


$base_out = array();

// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
    // IDs were necessary before, to keep track of ports (by id), 
    // but they bother json now, so we do...
    $base_out[] = $record;
}

$json = json_encode($base_out);

echo $json;

Haven't had the time to test or think twice about it, but again, I hope it conveys the idea...

Comments