duanlaiquan8174 2016-09-23 08:07
浏览 78
已采纳

在不使用递归PHP的情况下迭代父级子级

I have a database table with parent-children rows, one parent-many children, linked by field "parent".

I know how to loop and print a jerarquy structure by using recursive function in PHP, but when I try to reproduce it with a single loop code, I cannot present the data in the same format. This sample of code lists all items in the database table, but not ordered, it prints first the top level, and I want the classical:

  Top 1 >> Level 1 >> Level 2 >> Level 3
  Top 2 >> Level 1
  Top 3 >> Level 1 >> Level 2

  $parent = array();
  array_push($parent, 0);
  while(!empty($parent)){
    foreach($parent as $key => $mother){
      unset($parent[$key]);     
      $sql = "SELECT * FROM levels WHERE parent = " . $mother;
      $res = mysql_query($sql);
      while($row=mysqli_fetch_object($res)){
        print $row->name . "<br />";
        array_push($parent, $row->id);
      } // while
    } // foreach
  } // while

The result of this code is

Top 1 Top 2 Top 3 Level 1 ...

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 vsc C++ 终端开头有大量空行
      • ¥20 【matlab】运输问题优化问题。
      • ¥15 nodejs express 和 axios 前后端对接,数据体类型
      • ¥15 fluent计算后处理中如何把质量分数和摩尔分数转化为体积分数
      • ¥20 asn1c编码问题,懂asn1的人很简单
      • ¥15 使用vs2019开发的动态链路库在win7环境下使用有问题
      • ¥15 MFC滚动条如何正确使用
      • ¥15 缓冲区算法求面积,基于文献
      • ¥50 电路PCB原理图设计AD19
      • ¥15 openstack 云平台搭建 创建实例错误