Question

I want to group subcateogries within categories. The subcategories can have any number of elements such as this:

Output:

category #1
    item 1 
    item 2
    item 3

category #2
   item 1 
   item 2
   item 3
   item 4
   item 5

My initial plan is to use a multidimensional array like this:

$categories = array(
'cateogy_name_1' => array(
    1 => 'item_1',
    2 => 'item_2',
    ...
),
'cateogy_name_2' => array(
    1 => 'item_1',
    2 => 'item_2',
    3 => 'item_3',
    4 => 'item_4',
    5 => 'item_5',

    ...
),
....
);

My code so far...

$categories = array();
$result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY     
`catagory_id` ORDER BY `catagory_id`");  //retreive all categories and sub-categories

while($row = mysql_fetch_array($result))
 {
    //Get Categories and create arrays inside a single array
    //I'm stuck here, not sure how to initialize the multi-dimensional array
 }

foreach // Put all subcategories within the correct categories

        // I'm stuck here. How would I get the subcategories and put 
        // them into the correct category?

Okay so my questions are:

  1. How do I select categories and put them into their own arrays within a multidimensional array?

  2. How do I then put the subcategories inside the appropriate category arrays?

  3. And last, how do I print out an entire multidimensional array that can have any number of subcategories?

Was it helpful?

Solution

You should first get all the subcategories and categories on one queries:

SQL:

SELECT     sub_category_id, 
           category_id,
           sub_category_name,
           category_name           
FROM       sub_categories a
INNER JOIN categories b
    ON     a.category_id=b.category_id

PHP:

$categories = array();
while ($row = mysql_fetch_assoc($result)) {
    $cat_name = $row['category_name'];
    $sub_cat_id = $row['sub_category_id'];
    $sub_cat_name = $row['sub_category_name'];
    $categories[$cat_name][$sub_cat_id] = $sub_cat_name;
}

var_dump($categories);

OTHER TIPS

Note: You should not be using the deprecated mysql_* functions. Use PDO or something similar instead.

$categories = array();
while($row = mysql_fetch_assoc($result))
{
    $cat = $row['category_id'];
    $categories[$cat][] = $row['product_name'];
}

Like that?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top