Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive loop for category
    primarykey
    data
    text
    <p>I'm trying to implement a category system on my website. The problem is that a category can have child. So far, my table <code>category</code> looks like that : </p> <pre><code>id, name, parent_id </code></pre> <p>So far, I made a loop, but it only works for 2 levels. Here is my code : </p> <pre><code>for($i=0;$i&lt;count($data);$i++){ $tree[$data[$i]-&gt;name] = array(); for($j=0;$j&lt;count($data);$j++){ if($data[$j]-&gt;parent_id == $data[$i]-&gt;id){ $tree[$data[$i]-&gt;name][] = $data[$j]-&gt;name; } } } </code></pre> <p>It return me an array as it : </p> <pre><code>Array ( [0] =&gt; Array ( [1] =&gt; Cat1 [children] =&gt; Array ( [12] =&gt; sub cat 1 [13] =&gt; sub cat 2 [14] =&gt; sub cat 3 ) ) [1] =&gt; Array ( [2] =&gt; Cat2 ) [2] =&gt; Array ( [3] =&gt; Cat3 ) ) </code></pre> <p>How can I make it efficient and recursive to have something more like : </p> <pre><code>Array ( [0] =&gt; Array ( [1] =&gt; Cat1 [children] =&gt; Array ( [12] =&gt; sub cat 1 [13] =&gt; sub cat 2 [14] =&gt; sub cat 3 [children] =&gt; Array ( [1] =&gt; sub sub cat 1 ) ) ) [1] =&gt; Array ( [2] =&gt; Cat2 ) [2] =&gt; Array ( [3] =&gt; Cat3 ) ) </code></pre> <p>Thanks for your help</p> <p><em><strong>EDIT</em></strong></p> <p>I'm working on Zend, and it return me the <code>data</code> as it : </p> <pre><code>Zend_Db_Table_Rowset Object ( [_data:protected] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 1 [name] =&gt; Cinema [type] =&gt; category [slug] =&gt; cinema [parent_id] =&gt; -1 ) [1] =&gt; Array ( [id] =&gt; 2 [name] =&gt; Horror [type] =&gt; category [slug] =&gt; horror [parent_id] =&gt; 1 ) </code></pre>
    singulars
    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.
    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