Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive PHP function for adjacency-list display
    primarykey
    data
    text
    <p>I have a DB like so:</p> <pre><code>id text parent 1 Parent 1 0 2 Child of 1 1 3 Sibling 1 4 Another Parent 0 5 A first child 4 </code></pre> <p>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:</p> <pre><code>class Data_Manager { public $connection = ''; public $collection = array(); function __construct() { $this-&gt;connection = mysql_connect('localhost', 'root', 'root'); $thisTable = mysql_select_db('data'); // error handling truncated } function get_all() { $arr = &amp;$this-&gt;collection; $this-&gt;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-&gt;recurseTree($row['id'], $level+1, $arrayNode[$row['id']]); } } } </code></pre> <p>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:</p> <pre><code>[ Parent1 =&gt; [ children =&gt; ['Child of 1', 'Sibling'] ], AnotherParent =&gt; [ children =&gt; ['First Child'] ] ] </code></pre> <p>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.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload