Tanja Posted July 6, 2013 Share Posted July 6, 2013 In my database are following fields: id, fatherid, motherid. There are four "starter-dogs" with id 1,2,3 and 4; now i want to count how many generations are between the starter and the dog (for each starter seperate). How can i loop the query (and count) until it reach id 1 (or 2)? Select fatherid from mytable where id = 222 Result (for example) 333 - not 1 - again Select fatherid from mytable where id = 333 ... Quote Link to comment https://forums.phpfreaks.com/topic/279910-count-generation-maybe-loop-until/ Share on other sites More sharing options...
requinix Posted July 6, 2013 Share Posted July 6, 2013 Sure: keep getting the fatherid in a loop until you end up with one of the starter dog IDs. $id = 222 while $id is not of a starter dog { $id = get fatherid of $id }(or another similar loop construct) Quote Link to comment https://forums.phpfreaks.com/topic/279910-count-generation-maybe-loop-until/#findComment-1439611 Share on other sites More sharing options...
Tanja Posted July 9, 2013 Author Share Posted July 9, 2013 ok, but here are same dogs more than one time in pedigree (the starter dogs). On father side the starterdog is in the 6. generation, on mother side in 9. generation. With this solution a called every fatherid so long until starter dog is reached (for father, grandfather, grandgrand...) I want the shortest distance to the starter dog... http://www.wolfdog-database.com/dog/dog.php?id=13425&gens=7 for example here the shortest distance to Sarik. In other cases the pedigree is over much more generations ;-) Quote Link to comment https://forums.phpfreaks.com/topic/279910-count-generation-maybe-loop-until/#findComment-1440054 Share on other sites More sharing options...
requinix Posted July 9, 2013 Share Posted July 9, 2013 (edited) Breadth-first search: every time you find a non-starter dog, append it to an array (as well as the "depth"). Use a while/array_shift() loop to keep pulling stuff off the array (you can't foreach) until you find a starter dog. $dogs = array(current dog); while($dog = array_shift($dogs)) { list($dog, $depth) = $dog; if $dog is a starter dog { return $depth; } else { $dogs[] = array($dog''s mother, $depth + 1); $dogs[] = array($dog''s father, $depth + 1); } } Edited July 9, 2013 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/279910-count-generation-maybe-loop-until/#findComment-1440082 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.