sql和PHP关系,父子关系PHP / MYSQL

我有这样一张桌子:

> 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值