Jump to content

Another Categories and Sub Categories Question


oldschool

Recommended Posts

 

I'm having to woes with my work at the moment.

 

tbl_cats (cat_id, cat_name, cat_parent)

 

-snip-

1 - Sales - NULL

2 - Wanted - NULL

3 - Announcments - NULL

4 - Household - 1

5 - Audio - 1

6 - Household - 2

7 - Household - 2

8 - Birthdays - 3

9 - Weddings - 3

-snip-

 

 

Using the various tutorials around etc I've manged to list the categories under each parent vertically but I'd like to group them into columns like the design attached shows. Could somebody spare 5 minutes of guidence please?

 

[attachment deleted by admin]

  • 3 weeks later...

ok, this morning I've engaged my brain and got a step closer..

 

SELECT c.cat_name, c.cat_id, Count( m.msg_id ) AS CountOfMsg FROM communitymessages_subcats c, communitymessages m WHERE m.msg_sub_cat_id = c.cat_id AND c.cat_parent = '46' GROUP BY c.cat_name

 

just for demostration purposes I've used a static value for cat_parent.

 

I need to loop the above query for each cat_parent.. clues?

 

sorry to keep bumping this, but I know it can be done, I just need a gentle nudge in the right direction.

I suggest you assign the whole query to an array...from there assign your sub cats to another array without making another query.use php loops. NEVER loop a query...a for loop would be great.

 

$strQuery = // your query
$qryResult = mysql_query($strQuery);
while($qryData = mysql_fetch_array($qryResult,MYSQL_ASSOC))
  $qryArray[] = $qryData;

// Loop to achieve the conditions you want

Something like this?

 

<?php
include '../test/db.php';

$sql = "SELECT cat_id, cat_parent, cat_name FROM tbl_cats";
$res = mysql_query($sql) or die (mysql_error()."<p>$sql</p>");

$cats = array();
while (list($id, $parent, $name)=mysql_fetch_row($res))
{
    $cats[$parent][] = array('id' => $id, 'name' => $name);
}


subcat_columns($cats, 0);

function subcat_columns (&$cats, $parent)
{
    echo '<table border="1">';
    /**
    * col headings
    */
    echo '<tr>';
        foreach ($cats[$parent] as $ar) echo "<th>{$ar['name']}</th>";
    echo '</tr>';
    
    /**
    * col items
    */
    echo '<tr valign="top">';
        foreach ($cats[$parent] as $ar) 
        {
            echo '<td>';
            list_subcats($cats, $ar['id']);
            echo '</td>';
        }
    echo '</tr>';
    echo '</table>';
}

function list_subcats (&$cats, $parent)
{
    if (isset($cats[$parent]))
    foreach ($cats[$parent] as $ar)
    {
        echo $ar['name'], '<br>';
        list_subcats ($cats, $ar['id']);
    }
}
?> 

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.