Jump to content

Categories dropdown with x amount of subcategories.


ram4nd

Recommended Posts

I want to make dropdown menu. I have a table where are categories and x amount of subcategories.

They will be displayed something like:

cat

-subcat

-subcat

--subcat

cat

-subcat

I figured I need some loop system. I was trying to do it with 2 foreach loops in while loop, but I got confused and I thought I'll ask help from people with more brain processing capabilities.

Adjacency list (parent id) or a Modified preorder algorithm (left and right values)?

I dont understand a word of it, but maybe this helps:

CREATE TABLE IF NOT EXISTS `categories` (
  `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `category_id` mediumint(9) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=26 ;

The category_id is now parent_id

I did it like this:

function get_categories()
{
$query = $this->db->query('SELECT * FROM categories ORDER BY name');
//return data
if($query->num_rows()>0) {
	static $refs = array();
	static $list = array();

	foreach($query->result_array() as $data) {
		static $id, $parent_id, $name;
		$id = $data['id'];
		$parent_id = $data['parent_id'];
		$name = $data['name'];

		$thisref = &$refs[$id];

		$thisref['parent_id'] = $parent_id;
		$thisref['name'] = $name;

		if($parent_id == 0) $list[$id] = &$thisref;
		else $refs[$parent_id]['children'][$id] = &$thisref;
	}
}
else return FALSE;
}

 

But I can't figure out how can I echo it? And yes I read the comments.

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.