mysql foreach循环 输出 树,通过PHP与mysql进行递归树遍历

I am creating a questionnaire for a client that requires the questions to be organized by 3 layers of levels. I've successfully created the U.I. however I've been trying for the last 3 hours to pull data from a database in such a way that everything loads in the right place. The database is organized like so by the client so I have no control over it:

id description parentId

1 Level 1 0

2 Level 2 0

3 Level 1a 1

4 Level 1b 1

5 Level 1a1 3

I have found a similar question to mine on the site but when I attempted it's solution I got the following on repeat infinetly:

Code:

function makeList($par_id = 0) {

//your sql code here

$result = mysql_query("SELECT * FROM pB_test WHERE parentId = $par_id");

$pages = mysql_fetch_array( $result );

if (count($pages)) {

echo '

  • ';

foreach ($pages as $page) {

echo '

', $page['description'];

makeList($page['parentId']);

echo '

';

}

echo '

';

}

}

makeList();

Output:

1

3

5

5

l

l

3

5

5

l

l

3

5

5

l

l

3

5

5

l

l

Does anyone know how to fix this and what the issue is exactly? Cheers

解决方案

Do this recursivly:

function printChildQuestions($parentid) {

$sql="SELECT * FROM pB_test WHERE parentID=$parentid";

$result=mysql_query($sql);

$i=0;

while (true) {

$row=mysql_fetch_array($result);

if (!$row) break;

if ($i==0) echo "

  • ";

$i=1;

echo '

'.$row['id'].' '.$row['description'].' '.$row['parentId'].'';

printChildQuestions($row['id']);

}

if ($i>0) echo '

';

}

printChildQuestions(0);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值