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.

Link to comment
Share on other sites

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 ;

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.