Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如果mysql表有嵌套记录,如何从该表中获取主值_Php_Mysql - Fatal编程技术网

Php 如果mysql表有嵌套记录,如何从该表中获取主值

Php 如果mysql表有嵌套记录,如何从该表中获取主值,php,mysql,Php,Mysql,我有一张像下面这样的桌子 id | name |parent ---| --- | --- 1 |vehicle|0 2 |car |1 3 |test |0 4 |maruti |2 5 |alto |4 6 |test2 |3 我的类别id为5。现在我想要ID5的第一个父类别 id 5的第一个父类别为1(车辆) 为此,我需要运行4个查询才能得到它 比如说, public function getParentCategory($catId) {

我有一张像下面这样的桌子

id | name  |parent
---| ---   | --- 
1  |vehicle|0 
2  |car    |1 
3  |test   |0 
4  |maruti |2 
5  |alto   |4 
6  |test2  |3
我的类别id为5。现在我想要ID5的第一个父类别

id 5的第一个父类别为1(车辆)

为此,我需要运行4个查询才能得到它

比如说,

public function getParentCategory($catId)
{
        $cat = mysql_fetch_array(mysql_query('select id,parent from category where id=$catId'));

        if ($cat['parent']  == 0) {

            return $cat['id'];

        } else {

            return $this->getParentCategory($cat['id']);
        }
}
现在,上述函数运行3次以获取category
alto


那么,有没有简单的方法可以在不递归运行查询的情况下更轻松地获得结果?

我认为您应该从db中获取所有类别,然后在php中选择current category。 范例

$categories = mysql_fetch_array(mysql_query('select id,parent from category'));
foreach($categories as $cat){
    $this->categories[$cat['id']][] = $cat;
}
选择类别:

public function getParentCategory($catId)
{
    if ($this->categories[$catId]['parent']  == 0) {
        return $this->categories[$catId]['id'];
    } else {
        return $this->getParentCategory($this->categories[$catId]['parent']);
    }
}

我不明白你到底想要什么?如果你有id,我想这是主键,但问题是什么?请参考我的答案:你能给我们展示一下你的架构吗