I have a DB like this:
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 am trying to capture the tree structure in which the parents are listed. I know another option (nested sets, in my opinion?), But now I will stick to this. Now I'm trying to get data from the database and into the structure of nested arrays 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 I would like to come up with some kind of nested associative array tree, but I cannot figure out how to do this. It seems that nothing is writing to the array that I enter, and I kind of lose myself in recursion. Can someone help me get this last hump that will lead to something like:
[ Parent1 => [ children => ['Child of 1', 'Sibling'] ], AnotherParent => [ children => ['First Child'] ] ]
And I'm less interested in the specific output form. It will be converted to JSON, and I have not yet written a client-side handler, so don't worry about the exact structure.
Thanks!
source share