oohoohoohooh
Programmer
Hi, I have a table setup called categories with the following structure:
- cat_id (primary key)
- subcat_id
- cat_name
If a category is within another category it's subcat_id would be the cat_id of the category it is within. This allows me to have unlimited subcats within subcats. Hope all is clear so far. I setup the following function to store the contents of the table in an array (so I don't have lots of queries):
Now I need some way of looping through the array to display the contents. This is where I get stuck as I'm not too great with arrays. Below is the kind of output I wish to display based on the array at the bottom:
I put print_r(get_categories()) so you could see the contents of the array we're dealing with and I got:
I'd appreciate it if you could help. Thanks
- cat_id (primary key)
- subcat_id
- cat_name
If a category is within another category it's subcat_id would be the cat_id of the category it is within. This allows me to have unlimited subcats within subcats. Hope all is clear so far. I setup the following function to store the contents of the table in an array (so I don't have lots of queries):
Code:
function get_categories() {
$cats = array();
$query = $GLOBALS['db']->query("SELECT * FROM " . $GLOBALS['config']['db']['prefix'] . "cats ORDER BY cat_id");
while ($cat = $GLOBALS['db']->fetch_array($query)) {
$cats[$cat['subcat_id']][] = $cat;
}
return $cats;
}
Now I need some way of looping through the array to display the contents. This is where I get stuck as I'm not too great with arrays. Below is the kind of output I wish to display based on the array at the bottom:
Code:
Books, Music, DVD
- Books
- DVD
- Music
- Pop
- Rock
- Video
Electronics & Office
- Electronics
- Mobile Phones
- Camera & Photo
I put print_r(get_categories()) so you could see the contents of the array we're dealing with and I got:
Code:
Array
(
[0] => Array
(
[0] => Array
(
[cat_id] => 1
[subcat_id] => 0
[cat_name] => Books, Music, DVD
)
[1] => Array
(
[cat_id] => 2
[subcat_id] => 0
[cat_name] => Electronics & Office
)
)
[1] => Array
(
[0] => Array
(
[cat_id] => 5
[subcat_id] => 1
[cat_name] => Books
)
[1] => Array
(
[cat_id] => 6
[subcat_id] => 1
[cat_name] => DVD
)
[2] => Array
(
[cat_id] => 7
[subcat_id] => 1
[cat_name] => Music
)
[3] => Array
(
[cat_id] => 8
[subcat_id] => 1
[cat_name] => Video
)
)
[2] => Array
(
[0] => Array
(
[cat_id] => 9
[subcat_id] => 2
[cat_name] => Electronics
)
[1] => Array
(
[cat_id] => 10
[subcat_id] => 2
[cat_name] => Mobile Phones
)
[2] => Array
(
[cat_id] => 11
[subcat_id] => 2
[cat_name] => Camera & Photo
)
)
[7] => Array
(
[0] => Array
(
[cat_id] => 26
[subcat_id] => 7
[cat_name] => Pop
)
[1] => Array
(
[cat_id] => 27
[subcat_id] => 7
[cat_name] => Rock
)
)
)
I'd appreciate it if you could help. Thanks