Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Maybe easier with OOP. Just sort the query by parentId</p> <p>Note: The listChildren method and the printout at the bottom is just there to show it is listed correctly. I did not interpret the question that the display was important.</p> <pre><code>class Element { public $id; public $name; public $parent = null; public $children = array(); public function __construct($id, $name) { $this-&gt;id = $id; $this-&gt;name = $name; } public function addChild($element) { $this-&gt;children[$element-&gt;id] = $element; $element-&gt;setParent($this); } public function setParent($element) { $this-&gt;parent = $element; } public function hasChildren() { return !empty($this-&gt;children); } public function listChildren() { if (empty($this-&gt;children)) { return null; } $out = array(); foreach ($this-&gt;children as $child) { $data = $child-&gt;id . ':' . $child-&gt;name; $subChildren = $child-&gt;listChildren(); if ($subChildren !== null) { $data .= '[' . $subChildren . ']'; } $out[] = $data; } return implode(',', $out); } } $elements = array(); $noParents = array(); while ($row = $connector-&gt;fetchArray($result)) { $elements[$row['id']] = $element = new Element($row['id'], $row['name']); if (isset($elements[$row['parent']])) { $elements[$row['parent']]-&gt;addChild($element); } else { $noParents[] = $element; } } foreach ($noParents as $element) { if ($element-&gt;hasChildren()) { echo "Element {$element-&gt;id} has children {$element-&gt;listChildren()}.\n"; } else { echo "Element {$element-&gt;id} has no children.\n"; } } </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