【问题标题】:How to print child categories of sub categories in hierarchical order如何按层次顺序打印子类别的子类别
【发布时间】:2024-01-15 03:04:01
【问题描述】:

我正在尝试按层次顺序打印类别,无论它们有多深,我一直在尝试但仅在第二级成功,如​​果它们是 3 或 4 级深度怎么办。我希望他们在下拉列表中打印

Tasks
 -hard task
 --simple task

Notes
 -hard note
 --simple note
 ---easy note

记录

$records = array(   
array( 'id'=>'1',  'parent'=>'0', 'name'=>'Tasks' ),    
array( 'id'=>'2',  'parent'=>'0', 'name'=>'Notes' ),    

array( 'id'=>'3', 'parent'=>'1', 'name'=>'hard task' ),
array( 'id'=>'4', 'parent'=>'3', 'name'=>'simple task' ),

array( 'id'=>'5', 'parent'=>'2', 'name'=>'hard note' ),
array( 'id'=>'6', 'parent'=>'5', 'name'=>'simple note' ),
array( 'id'=>'7', 'parent'=>'6', 'name'=>'easy note' ),
);

我正在尝试的代码

function print_records($records){

foreach ($records as $rec){

    echo $rec['name'];
    $get_parent = $rec['parent'];
    get_sub_cat($get_parent);
  }
}


function get_sub_cat($get_parent){

foreach ($get_parent as $rec){

    echo $rec['name'];
    $get_sub = $rec['parent'];
    get_sub_child_cat($get_parent);
  } 
}

在这里我完全迷路了!我见过递归,但不知道在这种情况下如何使用

【问题讨论】:

    标签: php recursion logic


    【解决方案1】:

    您需要的称为递归。思路是这样的:

    function printLeafs($node){
      echo $node->title;
    
      $leafs = getLeafs($node);
      foreach ($leafs as $leaf){
        printLeafs($leaf);
      }
    }
    

    有趣的是,同时有一个相同的问题:PHP Print indefinite categories tree

    更新:

    有效的解决方案是(从命令行执行):

    <?php
    
    $records = array(
        array( 'id'=>'1',  'parent'=>'0', 'name'=>'Tasks' ),
        array( 'id'=>'2',  'parent'=>'0', 'name'=>'Notes' ),
    
        array( 'id'=>'3', 'parent'=>'1', 'name'=>'hard task' ),
        array( 'id'=>'4', 'parent'=>'3', 'name'=>'simple task' ),
    
        array( 'id'=>'5', 'parent'=>'2', 'name'=>'hard note' ),
        array( 'id'=>'6', 'parent'=>'5', 'name'=>'simple note' ),
        array( 'id'=>'7', 'parent'=>'6', 'name'=>'easy note' ),
    );
    
    printLeafs($records, 0);
    
    function printLeafs($records, $id, $depth = 0){
        if ($id) {
            $node = getNode($records, $id);
            echo str_pad('', $depth, '-') . $node['name'] . "\n";
        }
    
        $leafs = getLeafs($records, $id);
        foreach ($leafs as $leaf){
            printLeafs($records, $leaf['id'], $depth + 1);
        }
    }
    
    function getNode($records, $id){
        foreach ($records as $rec){
            if ($rec['id'] == $id){
                return $rec;
            }
        }
    
        throw new \Exception('id "' . $id . '" not found');
    }
    
    function getLeafs($records, $parent_id){
        $result = [];
        foreach ($records as $rec){
            if ($rec['parent'] == $parent_id){
                $result[] = $rec;
            }
        }
    
        return $result;
    }
    

    我也建议使用对象。

    【讨论】:

    • 哦,这很有趣,什么同时发生
    • 你能不能按照我的方式做以便更好地理解,我一直在尝试,但完美的解决方案会让我很开心
    最近更新 更多