I have a DB like so:
id text parent
1 Parent 1 0
2 Child of 1 1
3 Sibling 1
4 Another Parent 0
5 A first child 4
So I'm trying to capture a tree structure my listing the parents. I'm aware of the other option (nested sets I think?) but I'm going to stick with this for now. I'm now trying to get the data out of the DB and into a nested array structure in PHP. I have a function like this:
class Data_Manager
{
public $connection = '';
public $collection = array();
function __construct() {
$this->connection = mysql_connect('localhost', 'root', 'root');
$thisTable = mysql_select_db('data');
// error handling truncated
}
function get_all() {
$arr = &$this->collection;
$this->recurseTree('', 0, $arr);
var_dump($arr);
}
function recurseTree($parent, $level, $arrayNode) {
$result = mysql_query('SELECT * FROM tasks WHERE parent="' . $parent . '";');
while ($row = mysql_fetch_array($result)) {
$row['children'] = array(); //where I'd like to put the kids
$arrayNode[$row['id']]= $row;
$this->recurseTree($row['id'], $level+1, $arrayNode[$row['id']]);
}
}
}
So what I'd like to come out with is some kind of nested tree of associative arrays, but I can't figure out quite how to do that. Nothing seems to be writing to the array I pass in, and I'm sort of losing track of myself in the recursion. Can anyone help get me over this last hump that will result in something like:
[
Parent1 => [
children => ['Child of 1', 'Sibling']
],
AnotherParent => [
children => ['First Child']
]
]
And I'm less concerned with the specific form of the output. It will be turned into JSON and I haven't dealt with writing up the client-side handler yet, so no worries on exact structure.
Thanks!