父/子关系PHP/MYSQL


Parent Child Relationships PHP/MYSQL

我有一个这样的表:

  • id
  • <
  • 名称/gh>
  • parent_id

然后我想根据它们的id选择某些行,所以像这样:

SELECT * 
  FROM TABLE 
 WHERE id IN ('1', '5', '8', '9', '35')  

我想,从这个查询,也显示父/子关系,如:

id   parent  
-----------
1    0  
5    1  
8    0  
9    8  
35   9  

所以最终输出看起来像这样:

1  
--5  
8   
--9  
 ----35  

我是否在mysql之外这样做,我尝试过使用数组,但无法弄清楚,或
我是否在MYSQL中这样做,我也不知道怎么做。

这是我能想到的,似乎工作得很好。

ps -不好意思,格式不太清楚:( (fixed?)

  1. 我从MYSQL中获取parent_id和id并将其放入数组中数组键是id,值是父元素,在MYSQL的while循环中,像这样:$testarray[$id] = $parent_id;
  2. 然后我通过下面的函数运行它,它按照我需要的方式排序。

    function retrieveSubTree($parent, $myarray) {
        $tempArray = $myarray;
        $array = array();           
        //now we have our top level parent, lets put its children into an array, yea!
        while ($child = array_search($parent, $tempArray)) {
            unset($tempArray[$child]);
            //now lets get all this guys children
            if (in_array($child, $tempArray)) {
                $array[$child] = retrieveSubTree($child, $tempArray);
            } else {
                $array[$child] = true;
            }
        }//end while
        return (!empty($array)) ? $array : false;
    }
    function retrieveTree($myarray) {
        $array = array();
        $counter = 0;
        foreach ($myarray as $key => $value) {
            $child = $key;
            $parent = $value;
            //if this child is a parent of somebody else
            if (in_array($child, $myarray) && $parent != '0') {
                while ($myarray[$parent] != '' && $myarray[$parent] != '0') {
                    $newparent = $myarray[$parent];
                    $parent = $newparent;
                }
                if (!array_key_exists($parent, $array)) {
                    $array[$parent] = retrieveSubTree($parent, $myarray);
                }
            } else {
                //now make sure they don't appear as some child
                if (!array_key_exists($parent, $myarray)) {
                    //see if it is a parent of anybody
                    if (in_array($child, $myarray)) {
                        $array[$child] = retrieveSubTree($child, $myarray);
                    } else {
                        $array[$child] = true;
                    }
                }//end if array key
            }//end initial in array
        }//end foreach
        return (!empty($array) ? $array : false);
    } 
    $test = array(
        '1'=>'15',
        '2'=>'1',
        '3'=>'1',
        '4'=>'0',
        '5'=>'0',
        '6'=>'4',
        '7'=>'6',
        '8'=>'7',
        '9'=>'2',
        '10'=>'9'
    );
    print_r(retrieveTree($test)); 
    

如果不改变表结构,则需要递归,而MySQL不支持递归。你得去别的地方做。您可以在PHP中编写递归函数,例如,使用宽度优先搜索来构建数组。在这里,看起来您正在使用parent_id(0)来表示顶级对象。你可以搜索你的结果,并向你的数组中添加父元素为0的所有对象,这将给你一个包含1和8的数组。然后你可以递归:找到父元素为1的所有结果,并将其作为子数组添加到1;然后找到父元素为8的所有结果,并将它们添加为8的子数组。在每一关继续这样做,直到你的结果用完。

正如其他海报指出的,如果你可以改变表结构,你可以在MySQL中本地做到这一点。