PHP - Rearrange Tree Structure
Hey guys, I have a bunch of categories and products in a tree format. For several reasons I need to restructure them from the tree format into a flattened format.
I have 2 arrays, one full of categories, the other products. Each category and product has an ID, and a reference to it's parent's ID. The top level categories reference to 0. What I need is to have the categories output like thus: Top Level Categories: Category 1 Category 2 Category 1 Sub category 1 Sub category 2 Category 2 Sub category 3 Sub category 4 Sub category 1 Product 1 Product 2 Sub category 2 Product 3 Product 4 Sub category 3 Product 5 Product 6 Sub category 4 Product 7 Product 8 There could be an unlimited number of sub categories within categories before we get to products, so this needs to be done through a function, however I cannot for the life of me think how to do this. Initially I thought about using 2 arrays, a buffer of categories outputted, and a queue of categories to be outputted, but quickly realised that when I go more than 2 layers deep I can't keep track of the queue's properly. Similar TutorialsHi, I am working on a project, where i want to add sub-sections within a section , and add once again adding sub-subsection under that section. How to make a table structure for that, any idea please Thanks, Hi, I use this code (found in post http://www.phpfreaks.com/forums/index.php?topic=205633.0) to create a tree structure of categories and subgategories. Code: [Select] $prevcat = ''; $prevsubcat = ''; $sql = "SELECT * FROM $tbl_name ORDER BY categ, subcateg"; $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR); while($row = mysql_fetch_assoc($result)) { $cat = $row['categ']; $subcat = $row['subcateg']; $item = $row['itemname']; $description = $row['itemdesc']; if($cat != $prevcat){ echo $cat.'<br />'; echo 'sc '. $subcat.'<br />';//if the category has changed, we also want to show the new subcat }elseif($subcat != $prevsubcat){ echo $subcat.'<br />'; } echo 'it '.$item.'<br />'; echo 'desc '.$description.'<br />'; $prevcat = $cat; $prevsubcat = $subcat; } The above code works fine but I am trying to figure out how to count results of the deepest subcategory, so I will be able to change cell color or have results presented in two colums (left and right). Example: - main category 1 -- subcategory under category 1 ------ result 1 ------ result 2 ------ result 3 - main category 2 -- subcategory under category 2 ------ result 1 ------ result 2 - main category 3 -- subcategory under category 3 ------ result 1 ------ result 2 ------ result 3 ------ result 4 etc I want to count results under each subcategory, so on the above example I should have: 3 results for category 1 2 results for category 2 4 results for category 3 Any suggestions? Thank you. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=347192.0 Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! When having different levels of directories, using relative paths will not work anymore, for example: controller - authentication File 1: include('../../model/header.php') model File 2: header.php view File 3. style.css The header.php file includes the css file with a relative path, but the problem is it includes it as follows: ../view/style.css When now the header.php file gets included into File 1 in the folder "authentication", then the css file will not be accessible anymore, for it to be accessible you would have to go two directories up. In this sense my question is, what would be the proper path structure for a folder structure with multiple levels? Should I rather use absolute paths, I am not so prone of absolute path. What if the folders changes a bit, or the domain changes, or the location changes? yeah... in norway, we use dd.mm.yyyy, but mysql date uses yyyy.mm.dd.. Is there any php lines i can use to rearrange the input dates? And also, rearrange the date when i query the mysql for the dates? Hi, I wrote a piece of code for doing a recursive printing of all the leaf nodes. But it is not moving beyond one or two levels. Here is the code: $root = array( "paa" => array ( "adi1" => array ( "cir1" => array ( "aka", "ra", "vinodh","dkido" ), "cir2" => array ( "muta", "la" ), "cir3" => array ( "ezut", "telAm" ), "cir4" => array ( "ati" ) ), "adi2" => array ( "cir1" => array ( "paka", "vaV" ), "cir2" => array ( "mutaR", "RE" ), "cir3" => array ( "ula", "ku" ) ) ) ); function traverse($ar) { foreach($ar as $key=>$value) { echo "inside loop of ".$key."<br/>"; if(is_array($value)) { return traverse($value); } else { echo $key."==>".$value."<br/>"; } } } traverse($root); The output I get is: inside loop of paa inside loop of adi1 inside loop of cir1 inside loop of 0 0==>aka inside loop of 1 1==>ra inside loop of 2 2==>vinodh inside loop of 3 3==>dkido It does not seem to visit the other nodes. Anything I missed here ? V Hey guys i need to create a genealogy tree view in PHP and i have no idea on how to get started ... Is there existing class's for that out there? Any recomandations on the "how to"? Maby flash/xml is better? ... I am lost ... Hi guys I need help writing a php script I have a table 'categories' with fields 'id' 'cat_name' 'parent_id' the 'parent_id' is just an the id field.. I want to create a way to have unlimited sub categories so I can have categorie -> sub-categories categories -> sub-categories -> sub-categories categories -> products Can somebody please have a look at this. The Problem I am having is that only 1 entry for each month goes into the tree and for the life of me I can't figure out why. Code: [Select] $queryyp = "SELECT YEAR(date) as year, MONTHNAME(date) as month, title FROM monsterpost ORDER BY date DESC"; // query to get the rows you want in the order that you want them, with the year and monthname specifically selected as well $resultyp = mysql_query($queryyp); $last_heading = null; // remember the last heading (initialize to null) while($rowyp = mysql_fetch_assoc($resultyp)){ $new_heading = $rowyp['year']; // get the column in the data that represents the heading $new_subheading = $rowyp['month']; // get the column in the data that represents the subheading if($last_heading != $new_heading){ // heading changed or is the first one $last_heading = $new_heading; // remember the new heading $last_subheading = null; // (re)initialize the subheading // start a new section, output the heading here... echo "<ol class=\"tree\"><li><label for=\"folder1\">{$rowyp['year']}</label> <input type=\"checkbox\" id=\"folder1\" /></li></ol>"; } // subheading under each heading if($last_subheading != $new_subheading){ // subheading changed or is the first one $last_subheading = $new_subheading; // remember the new subheading // start a new section, output the subheading here... echo "<ol><li><label for=\"subfolder1\">{$rowyp['month']}</label> <input type=\"checkbox\" id=\"subfolder1\" />"; } // output each piece of data under a heading here... echo "<ol><li class=\"file\">{$rowyp['title']}</li></ol></li></ol></li></ol>"; } hi all. I am working on a MLM project in which i have more than 30,000 members followed by the root member,i have to store member automatically in binary tree form like 1 is root 2 is child of 1 3 is child of 1 Then 4 is child of 2 5 is child of 2 and so on ...... i have to design database for that. please help I am trying to display binary tree level wise. Breadth-first tree traversal can be used in it.Can anyone point me towards its logic or point me towards a good tutorial. Hello everybody, i am working on n level category tree structure, for your information the category tree structure image is attached with this post. Let's consider, each of the category have hundreds( n level ) of category in each, i want to traverse each category without using recursive functions, reason being recursive functions are very slow, is there any way to do this?? Thanks, phpeid Hey guys, i am a college student and working on a project of mlm ad want to display the binary income tree,and also calculate the income that is given to each node. Please see the attachments for the binary tree structure and database table structure. Thanks. [attachment deleted by admin] I am trying to count left node of a binary tree.I made a function but my result is always 3 . Code:- Code: [Select] <?php include'config.php'; // Connect database function leftcount($node) //Function to calculate leftcount { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild'])) { $count++; leftcount($array['lchild']); } if(!empty($array['rchild'])) { $count++; leftcount($array['rchild']); } $totalcount = 1 + $count; return $totalcount; } $parent = "2"; $left = leftcount($parent); echo $left; ?> Can someone please point the error in my logic ? I searched google but i only got scripts with classes and i don't want to use classes. This is my first try to display binary tree so please go easy on me. I am trying to display binary tree using array. The values are stored in mysql. Structure of mysql- Code: [Select] CREATE TABLE IF NOT EXISTS `tree` ( `parent` int(7) NOT NULL, `rchild` int(7) NOT NULL, `lchild` int(7) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Display should look like Code: [Select] 1 ______|______ | | 2 3 ______|______ | | 4 5 My Code till now- Code: [Select] <?php include 'connection.php'; $rsearch = "SELECT rchild FROM tree WHERE parent='".$parent."'"; $lsearch = "SELECT lchild FROM tree WHERE parent='".$parent."'"; $rexec = mysql_query($rsearch); $lexec = mysql_query($lsearch); while($rrow = mysql_fetch_assoc($rexec)) // Putting right branch in an array first { $rtree[$i][0] = $rrow['parent'] ; $rtree[$i][1] = $rrow['lchild'] ; $rtree[$i][2] = $rrow['rchild'] ; $i++; } while($lrow = mysql_fetch_assoc($lexec)) // Putting left branch in an array { $ltree[$j][0] = $lrow['parent'] ; $ltree[$j][1] = $lrow['lchild'] ; $ltree[$j][2] = $lrow['rchild'] ; $j++; } function displaytree($parent,$array) { // Im stuck here. Can someone please help me with it } ?> I am stuck at displaying the tree function. Can someone please point me in the right direction ? hi guys. i want to implement a referral system. a member can only refer using a form in the memebers area. on the referral form, i have a hidden field which is his referral id and a unique code (md5 generated link) and a field for the email address he wants to refer. once he sends the mail, a referal link (md5 generated, for uniqueness and to curb cheating) is sent to the email so that once he clicks, it takes him/her to the registration area. on my database table referrer_uid - the unique id of person referring someone referred_uid - the unique id of person being referred ref_code - the md5 generated code which is used on the link sent referred_email - the email address of the person being referred status - once a member sends a refer link, status is set to Referal sent date_referred - the date the refering took place date_accepted - the day the referred was accepted (i dont want this to change on clicking a referal link or registration cos not everyone gets accepted to avoid spurious referals) my question is how do i create a traversal tree with this. i read about traversal tree on sitepoint but when i tried to implement the examples, it didnt work for me and i noticed it was an old post. note: i intend giving points based on the child/tree and it could be as deep as possible. also if my method is wrong, ideas are higly appreciated. thanks Hello, I am currently working on a multi level marketing system requiring a lot of special features than the regular. It has 7 different levels with which you have move to the next level as your downlines qualify for the previous levels respectively. I am quite stuck on the tree structure. Here is how the plan details **1st stage** is 3 direct downlines only **2nd stage** 9 people from the direct 3 should qualify for 1st stage making total of 30, that mean 3 from 1st leg,3 from 2nd leg ,3 from 3 leg
**stage 3** ,9 people from the 30 should qualify for 2nd stage and it should fall on the direct 3
I need help with these first three functions and I will work the rest out. Building a separate tree view for each of the stages. Thanks Hello, I am using Fancytree, I want to generate a file / folder tree but excluding all folders that are not from the current user.
Example: I want to create a tree structure with the user "Peter"
[Tree]
I have several problems: Here is my code: <?php $name_user = 'Peter'; // actualy not user :-( print_r(listFolders()); function listFolders($dir = __DIR__ . '/datausers') { $dh = scandir($dir); $name_user = "Peter"; $return = []; if (strpos($dir, "/datausers/PERSONNAL") !== false){ // PERSONNAL found ! if ($dir === __DIR__ . '/datausers/PERSONNAL') { print_r($dir); echo '</br>'; foreach ($dh as $item) { if ($item != '.' && $item != '..') { if (is_dir($dir . '/' . $item)) { // it's a folder $return[] = array( 'title' => $item, 'folder' => true, 'expanded'=> true, 'children' => listFolders($dir . '/' . $item, $key) ); } else { // it's a file $return[] = [ 'title' => $item, ]; } } } } if (strpos($dir, "/datausers/PERSONNAL/" . $name_user) !== false){ // Peter found print_r($dir); echo '</br>'; foreach ($dh as $item) { if ($item != '.' && $item != '..') { if (is_dir($dir . '/' . $item)) { // it's a folder $return[] = array( 'title' => $item, 'folder' => true, 'expanded'=> true, 'children' => listFolders($dir . '/' . $item, $key) ); } else { // it's a file $return[] = [ 'title' => $item, ]; } } } } } else { print_r($dir); echo '</br>'; foreach ($dh as $item) { if ($item != '.' && $item != '..') { if (is_dir($dir . '/' . $item)) { // it's a folder $return[] = array( 'title' => $item, 'folder' => true, 'expanded'=> true, 'children' => listFolders($dir . '/' . $item, $key) ); } else { // it's a file $return[] = [ 'title' => $item, ]; } } } } return $return; } ?> Please help me I'm desperate ... Edited July 6 by ScottMeyer |