Jump to content

Counting results on category and subcategory tree structure


whisperer19

Recommended Posts

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.

 

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;
...
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.