whisperer19 Posted May 29, 2011 Share Posted May 29, 2011 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. $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. Quote Link to comment https://forums.phpfreaks.com/topic/237787-counting-results-on-category-and-subcategory-tree-structure/ Share on other sites More sharing options...
seanlim Posted May 29, 2011 Share Posted May 29, 2011 Try initialising an array to store a counter, using the category names as keys. Untested: $count = array() while($row = mysql_fetch_assoc($result)){ ... $count[$cat] = array_key_exists($cat, $count) ? $count[$cat]+1 : 1; ... } Quote Link to comment https://forums.phpfreaks.com/topic/237787-counting-results-on-category-and-subcategory-tree-structure/#findComment-1222012 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.