PHP - Building A Tree With Foreach Loops
I'm trying to build a tree to display product groups, but I can't achieve what I want. There is a hierarchy for the tree which I need to follow:
1H I want to list all the categories (1H) with its subcategories(1HS), and it's subcategories (1HSMP). This is the code I'm currently using: <ul> <?php //Here we fetch category $categories_list = array(); if($stmt = $conn -> prepare("SELECT a.category, a.subcategory, a.subcategory1, a.category_description, a.subcategory_description, a.subcategory_description1, SUM(nsq.sales_amount) AS sales, SUM(nsq.sales_amount+nsq.cost_amount) AS RUC FROM dpb.articles a LEFT JOIN dpb.nav_sales_qty nsq ON nsq.article_no = a.article_no WHERE nsq.entry_type_desc = 'Prodaja' GROUP BY a.subcategory1")) { $stmt -> execute(); $stmt -> store_result(); $stmt -> bind_result($category, $subcategory, $subcategory1, $category_description, $subcategory_description, $subcategory_description1, $total_sales, $total_profit); while($stmt -> fetch()) { $categories_list[] = array('category' => $category, 'subcategory' => $subcategory, 'subcategory1' => $subcategory1, 'category_description' => $category_description, 'subcategory_description' => $subcategory_description, 'subcategory_description1' => $subcategory_description1, 'total_profit' => $total_profit, 'total_sales' => $total_sales); } $stmt -> close(); } foreach($categories_list as $key => $value) { ?> <li><?php echo $value['category'].' - '.$value['category_description']; ?> <ul> <?php //Here we filter subcategory if(strpos($value['subcategory'], $value['category']) === 0) { //Iterate over subcategory foreach ($value as $key2 => $value2) { debugVar($value2); ?> <li data-jstree='{"opened":true}'><?php echo $value2['subcategory'] . ' - ' . $value2['subcategory_description']; ?> <ul> <?php //Here we filter subcategory2 if (strpos($value['subcategory1'], $value['subcategory']) !== false) { ?> <li data-jstree='{"type":"file"}'> <?php echo $value['subcategory1']; ?> </li> <?php //Here we close subcategory1 if statement } ?> </ul> </li> <?php //Here we close subcategory if statement } } ?> </ul> </li> <?php //Close foreach loop } ?> </ul> The result I'm getting is attached in the photo, and it's not what I want! The result I need is the following: I find a category (1H), and then I find all of its subcategories which are 1H% (all that start with 1H) and display them bellow 1H. Then I iterate over all of these subcategories (example 1HS%, 1HP%, 1HRD%) and I find all of their subcategories which are starting with (1HS, 1HP, 1HRD) and display them. Example:
1H Can you please help me how to achieve that? I spent a lot of time, and I can't get the proper result.
Similar TutorialsI don't want to have to use two foreach loops. Code: [Select] foreach($verify_partners as $verified) { echo $verified; echo $id; if ($verified == $id) { ?> <div> Remove </div> <?php } } It prints out as Array6Array6 My goal here is to have it foreach group from the DB it'll create a new frameset with the groupName as the legend and then under each of those it will create another foreach for each of the fields inside of that group that has a enabled value of 0 from the db. Both queries work correctly. I just get trouble writing foreach loops and I'm not sure how this one is going to work out. Code: [Select] <?php session_start(); // Access the existing session // Include the database page require ('../../inc/dbconfig.php'); $defaultCharID = $_SESSION['defaultCharID']; $styleIDQuery = " SELECT characters.styleID FROM characters WHERE characters.ID = '" . $defaultCharID . "'"; $styleIDResult = mysqli_query ( $dbc, $styleIDQuery ); // Run The Query $row = mysqli_fetch_array( $styleIDResult, MYSQL_ASSOC ); $styleID = $row[ 'styleID' ]; $biofieldsQuery = " SELECT fields.*, groups.* FROM fields INNER JOIN groups ON fields.groupID = groups.ID WHERE groups.styleID = '" . $styleID . "' AND fields.styleID = '" . $styleID . "' AND groups.enabled = 0 AND fields.enabled = 0"; $biofieldsResult = mysqli_query ( $dbc, $biofieldsQuery ); // Run The Query $row = mysqli_fetch_array( $biofieldsResult, MYSQL_ASSOC ); $groupName = $row[ 'groupName' ]; ?> <script type="text/javascript"> $(document).ready(function() { }); </script> <!-- Title --> <div id="title" class="b2"> <h2>Character Management</h2> <!-- TitleActions --> <div id="titleActions"> <!-- ListSearch --> <div class="listSearch actionBlock"> <div class="search"> <label for="search">Recherche</label> <input type="text" name="search" id="search" class="text" /> </div> <div class="submit"> <button type="submit" id="search-button" class="button"><strong><img src="img/icons/search_48.png" alt="comments" class="icon "/></strong></button> </div> </div> <!-- /ListSearch --> </div> <!-- /TitleActions --> </div> <!-- Title --> <!-- Inner Content --> <div id="innerContent"> <form action="#" id="bioForm" > <fieldset> <legend><?php echo $groupName; ?></legend> <div class="field required"> <label for="matchType">Match Type Name</label> <input type="text" class="text" name="matchType" id="matchType" title="Match Type Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <input type="submit" class="submit" name="submitMatchType" id="submitMatchType" title="Submit Match Type" value="Submit Match Type"/> </fieldset> </form> </div> <!-- /Inner Content --> Hey forum, I am a new php user and am having some issues (probably pretty basic to the likes of more experienced users), I am trying to make a script that has 4 checkboxes and a submit button, the values of the checkboxes should be passed through the array using a foreach loop, I got the basic template setup but when trying to pass the array I ran into a few problems. If anyone would take a peek at my code and point me in the right direction it would be much appreciated. Thanks forum. Code: [Select] <html> <title>Toppings</title> <body> <p>What do you want on your pizza?</p> <form action="ProcessToppings.php" method="post"> <?php //define varialbes $Output_form = false; $submit = $_POST['submit']; if(isset($submit)) { if(empty($toppings)) { echo '<b>You forgot to choose a topping(s).</b>'; echo '<br>'; echo '<br>'; $Output_form = true; } else { $toppings=array("0", "1", "2", "3"); foreach ($toppings ['toppings'] as $order) { echo 'Your pizza will have these topping: ' . $toppings . '<br/>'; $Output_form = false; } } } ?> <input type="checkbox" name="toppings[0]" value="pepperoni" />Pepperoni<br /> <input type="checkbox" name="toppings[1]" value="sausage" />Sausage<br /> <input type="checkbox" name="toppings[2]" value="mushrooms" />Mushrooms<br /> <input type="checkbox" name="toppings[3]" value="olives" />Olives <p> <input type="submit" value="Place Order" name="submit" /></p> </form> </body> </html> Hi Guys, I'm really [confused] about this however what I have so far is create a simple HTML form, instructing the end user to enter a list of keywords with links to replace them with in the following format: A keywords followed by a comma and then URL and semicolon: For example: birds,http://www.birdwatching.com/; snakes,http://www.whales.com/; horses,http://www.horse.com/; What I have done next is split each word with its associated url after each newline and then placed all the words into 1 array and all the urls into another array, using the following code: preg_match_all('/(.*),(.*);/',$wordsurls, $phrase); $wds = $phrase[1]; $rurls = $phrase[2]; foreach($wds as $wd) { $words_array[] = $wd; } foreach($rurls as $rurl) { $urls_array[] = $rurl; } All that works perfectly fine but now I wish to search a string to find each of those keywords, and if they exist I would like to replace them with the URL. I believe this can be done using Parallel Array matching but do not know how to go accomplishing this. Could someone please help me? Thank you in advance. M Hey forum, I am a new php user and am having some issues (probably pretty basic to the likes of more experienced users), I am trying to make a script that has 4 checkboxes and a submit button, the values of the checkboxes should be passed through the array using a foreach loop, I got the basic template setup but when trying to pass the array I ran into a few problems. If anyone would take a peek at my code and point me in the right direction it would be much appreciated. Thanks forum. [attachment deleted by admin] I know there's something wrong with my code because the page never loads so there's somethign wrong with either the for loop or foreach loop. The topRankings variable is set correct and giving the right value. Code: [Select] <?php for ($i = 0; $i >= count($topRankings); $i++){ foreach($topRankings[$i] as $k=>$v) { $seperator = ($elements == $count) ? '' : '<hr />'; $name = (!isset($row['character_name'])) ? 'TBD' : $row['character_name']; $count++; ?> <li><span class="red"><?php echo $name; ?></span></li> <?php } } ?> Greetings, My first post here. I'm learning PHP as rapidly as I can, but I still have some basic questions. OK, I'm trying to run the Gallerific gallery script on my site. The way Gallerific works, it looks at an unordered list to populate the gallery. In each list item, it grabs a main image and a thumbnail image. I have folders that are created dynamically as a user uploads photos. There is a main folder and a "thumbs" sub-folder. That's all taken care of before the script comes into play I need to loop through both the main images and the thumbnails at the same time, and call each one in the list items. I know this code must be wrong, but I'll post it as a starting place. Can someone help me figure out how to do this correctly? Maybe I should not even be using foreach? Code: [Select] <div id="thumbs" class="navigation"> <ul class="thumbs noscript"> <?php foreach($cck->get( 'property_listing_images' )->value as $large){ foreach($cck->getValue( 'property_listing_images' )->value as $thumb1){ ?> <li> <a class="thumb" href="images/<?php echo $large->value; ?>" title="Title X"> <img src="images/<?php echo $thumb1->value; ?>" alt="Title X" /> </a> </li> </ul> <?php } ?> <?php } ?> </div> Thank you ahead of time for your help! Matthew This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 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 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>"; } 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, 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 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 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 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. 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 ? 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 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. 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. |