我有这样一张桌子:
> id
>名字
> 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-对不起格式化,无法搞清楚:((修复?)
>我从MYSQL中获取了我的parent_id和id并将其放入arraly,其中数组键是id,值是父类,因此在mysql的while循环中,类似这样:$testarray [$id] = $PARENT_ID;
>然后我通过下面的函数运行它,并命令它我需要它.
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));
标签:php,mysql,sql,hierarchical-data
来源: https://codeday.me/bug/20190710/1419812.html