Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Working with a nested set is a perfect case for recursion.</p> <p>Given your data:</p> <pre><code>$category = array( 'A' =&gt; array('left' =&gt; 1, 'right' =&gt; 9), 'B' =&gt; array('left' =&gt; 2, 'right' =&gt; 4), 'C' =&gt; array('left' =&gt; 5, 'right' =&gt; 8), 'D' =&gt; array('left' =&gt; 6, 'right' =&gt; 7), 'E' =&gt; array('left' =&gt; 10, 'right' =&gt; 11), ); </code></pre> <p>The following will break your nested set data down into a properly nested array in PHP:</p> <pre><code>function createTree($category, $left = 0, $right = null) { $tree = array(); foreach ($category as $cat =&gt; $range) { if ($range['left'] == $left + 1 &amp;&amp; (is_null($right) || $range['right'] &lt; $right)) { $tree[$cat] = createTree($category, $range['left'], $range['right']); $left = $range['right']; } } return $tree; } $tree = createTree($category); print_r($tree); </code></pre> <p>Output:</p> <pre><code>Array ( [A] =&gt; Array ( [B] =&gt; Array ( ) [C] =&gt; Array ( [D] =&gt; Array ( ) ) ) [E] =&gt; Array ( ) ) </code></pre> <p>Then you can flatten your proper tree into the format you want with the following:</p> <pre><code>function flattenTree($tree, $parent_tree = array()) { $out = array(); foreach ($tree as $key =&gt; $children) { $new_tree = $parent_tree; $new_tree[] = $key; if (count($children)) { $child_trees = flattenTree($children, $new_tree); foreach ($child_trees as $tree) { $out[] = $tree; } } else { $out[] = $new_tree; } } return $out; } $tree = flattenTree($tree); print_r($tree); </code></pre> <p>Output: </p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; A [1] =&gt; B ) [1] =&gt; Array ( [0] =&gt; A [1] =&gt; C [2] =&gt; D ) [2] =&gt; Array ( [0] =&gt; E ) ) </code></pre>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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