dongquxiao8545 2019-02-21 09:10
浏览 47
已采纳

PHP - SQL表中的嵌套数据树

I have an SQL table containing a list of parts with sub parts that go into them. I need to come up with a way of outputting the data into a tree to show what goes into what else.

The table is simply as below:

Part_Number | Sub_Part
1             1a
1             1b
1             1c
1a            1a0
1a            1a1
1b            1b0
2

So from that I would need to output something like this:

-1
--1a
---1a0
---1a1
--1b
---1b0
--1c
-2

I cannot think of a solution for this, I have tried using loops within loops to pull the information but the best I can get is a the first sub part of each layer: 1, 1a, 1a0.

<?php $lookup = ['1']; ?>
    <?php 
        x: 
        $i = $i . '-';
    ?>

    <?php foreach($lookup as $look) : ?>
        <p><?php echo $i . $look; ?></p>
        <?php $lookup = []; ?>

        <?php $query = mysqli_query($conn, "SELECT Sub_Part FROM `Bill_Of_Materials` WHERE Part_Number = '{$look}'"); ?>
        <?php while($search = mysqli_fetch_array($query)) : ?>
            <?php array_push($lookup, $search[0]); ?>
        <?php endwhile; ?>

        <?php goto x; ?>
    <?php endforeach; ?>

I am thinking that the best way to do this might be to create objects for each top level part then have a recursive loop to create objects for each sub part within it, and each within that etc.

Objects are quite new to me however, so is this possible?

  • 写回答

2条回答 默认 最新

  • doupian6118 2019-02-21 09:47
    关注

    I have managed to work this out myself, by creating an object which then searches the SQL table for sub parts and creates another object per sub.

    class part {
        function __construct($partNumber, $layer = '-') {
            echo $layer . $partNumber . '<br>';
    
            $conn = mysqli_connect('localhost', 'user', 'pass', 'database');
    
            if(!$conn) {
                die('Connection Failed: ' . mysqli_connect_error());
            }
    
            $subs = mysqli_query($conn, "SELECT Sub_Part FROM `Bill_Of_Materials` WHERE Part_Number = '{$partNumber}'");
    
            while($sub = mysqli_fetch_assoc($subs)) {
                $sub = new part($sub['Sub_Part'], $layer . '-');
            }
        }
    }
    
    $a = new part('123');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决