Note that there are some explanatory texts on larger screens.

plurals
  1. POSimple recursive tree in PHP / MySQL
    primarykey
    data
    text
    <p>I have this table in MySQL:</p> <pre><code>id name mother 1 grandma 0 2 myuncle 1 3 mymom 1 4 me 3 5 mysister 3 6 myson 4 7 new_grandma_son 1 </code></pre> <p>I almacenate this info in an array called <code>data[]</code></p> <pre><code>$data=array( array("id"=&gt;1,"name"=&gt;"grandma", "mother"=&gt;0), array("id"=&gt;2,"name"=&gt;"myuncle", "mother"=&gt;1), array("id"=&gt;3,"name"=&gt;"mymom", "mother"=&gt;1), array("id"=&gt;4,"name"=&gt;"me", "mother"=&gt;3), array("id"=&gt;5,"name"=&gt;"mysister", "mother"=&gt;3), array("id"=&gt;6,"name"=&gt;"myson", "mother"=&gt;4), array("id"=&gt;7,"name"=&gt;"new_grandma_son","mother"=&gt;1) ); </code></pre> <p>And for make a family tree I am using this recursive function:</p> <pre><code>function tree($data, $mom = 0, $level = 0){ foreach ($data as $row){ if ($row['mother'] == $mom) { echo str_repeat("-", $level).$row['name']."&lt;br&gt;"; tree($data, $row['id'], $level); } else $level++; } } </code></pre> <p>When I call the function <code>tree($data);</code> it shows this:</p> <pre><code>grandma -myuncle (level 1) -mymom ----me (level 4??) ---------myson (level 9??) ----mysister ----new_grandma_son (level 4??) </code></pre> <p>I have the mistake in the <code>else $level++;</code>, because is adding levels when <code>$row['mother'] != $mom</code>, going through all the rows, but I don't know how to make it. Anyone knows? Thank you.</p> <p><strong>Solution (By Frits van Campen):</strong></p> <pre><code> tree($data, $row['id'], $level+1); // (eliminate this else $level++; ) </code></pre> <p>Thanks!</p>
    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