Reputation: 2533
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:
How do I select categories and put them into their own arrays within a multidimensional array?
How do I then put the subcategories inside the appropriate category arrays?
And last, how do I print out an entire multidimensional array that can have any number of subcategories?
Upvotes: 0
Views: 2116
Reputation: 3187
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);
Upvotes: 2