Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating an array using recursive php from mysql
    text
    copied!<p>I need to create an array from a mysql database organized like so</p> <pre><code>id description parentId 1 Level 1 0 2 Level 2 0 3 Level 1a 1 4 Level 1b 1 5 Level 1a1 3 6 Level 1a1a 5 </code></pre> <p>So that the output is like this:</p> <pre><code>Level 1 Level 1a Level 1a1 Level 1a1a Level 1b Level 2 </code></pre> <p>However my current code only outputs to the second level and then makes every other child it's own parent. Below is the current code:</p> <pre><code>$query = "SELECT * FROM pB_test ORDER BY parentId ASC"; $result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error()); $tree = array(); while($row = mysql_fetch_assoc($result)) { if($row['parentId'] == 0) { $row['Children'] = array(); $tree[$row['id']] = array( 'id' =&gt; $row['id'], 'description' =&gt; $row['description'], 'parentId' =&gt; $row['parentId'] ); } else { $tree[$row['parentId']]['Children'][$row['id']] = $row['description']; } } $count = array_keys($tree); foreach ($count as $array) { ksort($tree[$array]['Children']); } echo print_r($tree, true); </code></pre> <p>Any help or nudge in the right direction would be great. Cheers</p> <p><strong>Update</strong>: Working Code</p> <pre><code> $results = array(); while($row=mysql_fetch_assoc($dbresult)) { $results[]=$row; $tree = null; foreach($results as $result) { $thisref = &amp;$refs-&gt;{$result['id']}; foreach($result as $k =&gt; $v) { $thisref-&gt;{$k} = $v; } if ($result['parentId'] == 0) { $tree-&gt;{$result['id']} = &amp;$thisref; } else { $refs-&gt;{$result['parentId']}-&gt;children-&gt;{$result['id']} = &amp;$thisref; } } $tree; // contains the newly sorted tree. } print_r($tree); </code></pre>
 

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