递归检查数据库中孩子的父母 [英] Recursively check the parents of a child in a database

查看:92
本文介绍了递归检查数据库中孩子的父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个CMS系统上接收这样的网址:

I'm working on a CMS system that receives urls like this:

/parent1/parent2/child/

/parent1/parent2/child/

现在只检查孩子很容易,但我认为您还应该检查父母的正确性和正确性.问题是我不确定如何执行此操作.

Now it's easy to check only the child but in my opinion you should also check if the parents are correct and in the right order. The problem is that I'm unsure on how to do this.

我正在使用mysql.该表的外观如下:

I'm using mysql. this is how that table would look:

CREATE TABLE IF NOT EXISTS `pages` (
  `id` int(11) NOT NULL auto_increment,
  `parent` int(11) NOT NULL default '0',
  `title` varchar(255) NOT NULL,
  `deleted` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

父级字段保留其他在父级字段中将用作父级的页面ID.

the parent field keeps other page ID's that will be used as parent when in the parent field.

推荐答案

好,我制定了自己的方法,请不要使用kohana,所以要使用kohana的查询生成器:

Ok I worked out my own method, Please not I'm using kohana so I'm using the query builder of kohana:

这段代码构建了我要使用的数组.

This piece of code builds the array I want to use.

public function build_array($parent = 0, $data = null)
{
    if(!$data)
    {
        $result = db::select('*')
            ->from($this->_table_name)
            ->as_assoc()
        ->execute($this->_db);

        foreach($result as $page)
        {
            $data['items'][$page['id']] = $page;
            $data['parents'][$page['parent']][] = $page['id']; 
        }
    }

    if (isset($data['parents'][$parent]))
    {
        $array = array();
        foreach ($data['parents'][$parent] as $item)
        {
            $array[$data['items'][$item]['slug']] = array(
                'id' => $data['items'][$item]['id'],
                'subitems' => $this->build_array($item, $data)
            );
        }
        return $array;
    }
}

这段代码运行的URL穿过数组,如果父级错误,它将被卡住:

And this piece of code runs the url trough the array it gets stuck if a parent is wrong:

public function get_id($page, $parents)
{    
    $array = $this->build_array();

    if(!empty($parents[0]))
    {
        foreach($parents as $parent)
        {
            $array = $array[$parent]['subitems'];
        }
    }

    return $array[$page]['id'];
}

注意:您需要发送给该功能的数据是:

Note: The data you need to send to this function is:

$page = 'child'; 
$parent = 'parent1/parent2';

这篇关于递归检查数据库中孩子的父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆