The method you're using in storing your data is called Adjacency List model. To be able to achieve what you require. Follow these steps.
1) Retrieve the parent elements and save them to an array / hash.
2) Iterate through the parent array and retrieve child elements using the id of the parent.
Save the result to an array and append as element of the current parent array using "children" as key.
3) JSON encode the resulting array.
<?php
$sql = "SELECT * FROM yourtable WHERE PARENT is NULL or PARENT = 0";
$result = $db->query($sql); //a valid MySQL database adapter with a
//"query" method which returns the full result set.
$arr = array();
foreach($result as $row) {
$sql = "SELECT * FROM yourtable WHERE PARENT = {$row['id']}";
$result2 = $db->query($sql);
$row["children"] = $result2;
$arr[] = $row;
}
echo json_encode($arr);
?>
For more info about retrieving data hierarchy on these type of table, read Rum's post on Retrieving Data Hierarchies on a SQL Table.
Also, take precaution in this implementation. Although it looks easy to implement, watch out for the number of iterations involving external resource calls, in this case your database server. Iteratively calling queries beats the crap out of it causing performance problems in the future. If that is the case, you can apply a technique similar to Kendall Hopkins (though I'm not sure why he used by-ref call on $row). More info about iterative external resource calls here.
<?php
$sql = "SELECT * FROM yourtable";
$result = $db->query($sql);
$arr = array();
//re-index the result array based on their actual IDs
foreach ($result as $row) {
$arr[$row['ID']] = $row;
}
foreach ($arr as $item) {
if (!empty($item["PARENT"]) && $item["PARENT"] != 0) {
$arr[$item["PARENT"]]["children"][] = $item;
//unset the discovered child item to clean-up array and release memory allocation
unset($arr[$item["ID"]]);
}
}
echo json_encode($arr);
?>