Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to loop over looped elements in Php?
    primarykey
    data
    text
    <p>I'm creating a tree-structure of categories with parentid's which can be called from children in such a way:</p> <pre><code>ID | Name | ParentID 1 1 0 2 2 1 3 3 2 4 4 1 </code></pre> <p>Resulting in this:</p> <pre><code>1 = 1 2 = 1 -&gt; 2 3 = 1 -&gt; 2 -&gt; 3 4 = 1 -&gt; 4 </code></pre> <p>which means <strong>3 is a child of 2</strong>, which is a child of 1.</p> <p>when trying to get this idea (with the -> to show what relations are set) I only get to the second grade (1 -> 2) but not to the third (1->2->3) because of the looping function I use for it.</p> <pre><code>//put all ID's in an array while ($row2 = $connector-&gt;fetchArray($result2)){ $id = $row2['ID']; $parents[$id] = $row2['name']; } // show the tree-structure while ($row = $connector-&gt;fetchArray($result)){ if($row['parentid']!=0)echo $parents[$row['parentid']].' -&amp;gt; '; echo $row['name'].' - &amp;nbsp;&amp;nbsp; '; echo '&lt;br&gt;'; } </code></pre> <p>I'd like two things to change:</p> <blockquote> <ol> <li>have the code automatically generate a tree sized as necessary.</li> <li>in the while-loops i have to select the $result twice (once as $result, once as $result2) to make it work. these $result's have exactly the same database-query:<br/><code>SELECT ID,name,parentid FROM categories</code></li> </ol> </blockquote> <p>to fetch results from. I'd like to only declare this once.<br/> <br/> <br/> <br/> <strong>Thanks for all the good answers. I've gone with the easiest, less-code-to-implement approach:</strong></p> <pre><code>$result = $connector-&gt;query('SELECT ID,name,parentid FROM categories'); // Get an array containing the results. $parents = array(); while ($row = $connector-&gt;fetchArray($result)){ $id = $row['ID']; $parents[$id] = array('ID' =&gt; $row['ID'],'name' =&gt; $row['name'],'parentid' =&gt; $row['parentid']); } foreach ($parents as $id =&gt; $row){ $pid=$id; $arrTmp= array(); do { // iterate through all parents until top is reached $arrTmp[]=$pid; $pid = $parents[$pid]['parentid']; }while ($pid != 0); $arrTmp = array_reverse($arrTmp); foreach($arrTmp as $id){ echo $parents[$id]['name'].' -&amp;gt; '; } echo '&lt;br&gt;'; } </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.
    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