如何按层次顺序打印子类别的子类别

时间:2017-10-27 08:22:07

标签: php recursion logic

我试图按层次顺序打印类别,无论它们有多深,我一直在努力,但只有第二级成功,如​​果它们是3或4级深度则会怎样。我希望他们像下载一样打印

mvn exec:java

记录

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' ),
);
在这里,我完全迷失了!我已经看过递归但不确定如何在这种情况下使用

1 个答案:

答案 0 :(得分: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;
}

我也建议使用对象。