gibigbig Posted November 8, 2015 Share Posted November 8, 2015 This is my database structure: http://www.awesomescreenshot.com/image/733881/57d01b042ca99b9a36dde90dd6640cdc I would like to loop through all the child elements (those who's parent_id is set to the data_id within the same table). Therefore those with "parent_id" as "0" are parents, and those with parent_id with a number in it is a child. I would like help creating a function that will generate tables, with the table itself as the parent, and all the rows within it would be children of that parent. There is only one layer of depth in this project (one parent and one child layer always. ). Can anyone help, or would want a more detailed description? Thank you, and looking forward to a reply. Quote Link to comment https://forums.phpfreaks.com/topic/299363-help-with-parentchild-array-relationship/ Share on other sites More sharing options...
Barand Posted November 8, 2015 Share Posted November 8, 2015 You would join the table to itself on data_id/parent_id Example SELECT p.item_id as parent_item , p.alias as parent_alias , p.type as parent_type , c.alias as child_alias , c.type as child_type , c.name as child_name FROM item p LEFT JOIN item c ON p.data_id = c.parent_id WHERE p.parent_id = 0 ORDER BY parent_item; When you process the results, check for a change in the parent_item value. When it changes, close off the previous table and start a new one for the new item. Example $db = new mysqli(HOST, USERNAME, PASSWORD, 'darius'); $sql = "SELECT p.item_id as parent_item , p.alias as parent_alias , p.type as parent_type , c.alias as child_alias , c.type as child_type , c.name as child_name FROM item p LEFT JOIN item c ON p.data_id = c.parent_id WHERE p.parent_id = 0 ORDER BY parent_item"; $currItem = 0; $res = $db->query($sql); while (list($parent_item,$parent_alias,$parent_type,$child_alias,$child_type,$child_name) = $res->fetch_row()) { if ($parent_item != $currItem) { // has value changed? if ($currItem) { echo "</table>\n"; // close table (if we have one) } echo "<table border='1'><caption>$parent_alias</caption>\n"; $currItem = $parent_item; // reset current item value } echo "<tr><td>$child_alias</td><td>$child_type</td><td>$child_name</td></tr>\n"; } echo "</table>\n"; // close final table Quote Link to comment https://forums.phpfreaks.com/topic/299363-help-with-parentchild-array-relationship/#findComment-1526002 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.