算法:分类树排序


Algorithm: Category Tree Sorting

我已经建立了一个"无限深度"分类系统,该系统存储在数据库中,其中包含三条重要信息:

  • 类别ID
  • 父类别ID
  • NodePath

前两个是不言自明的,但最后一个需要澄清。如果类别是#20,其父级是#10,父级是#5,则NodePath看起来像5:10:20。通过这种方式,我可以递归地找到一个类别父分支。

我正在寻找一种方法,从数据库中获取每个类别,然后以某种方式对它们进行排序,结果是这样的数组:

array(
   0 => array(
      3 => array(
         7,
         13,
      ),
      5,
   ),
   1 => array(
      6,
      9
   ),
);

本质上,这是根据前面描述的NodePath结构创建的树层次结构的映射。

我想出了这样的东西:

 $tree = array();
 foreach( $categories as $category )
 {
    // A NodePath Example is "1:7:13:24" where 1 is the root category,
    // 24 is the "leaf" or end node, and the other numbers are sub categories
    // in order.
    $nodes = explode( ":", $category->NodePath );
    $lastNode = &$tree;
    foreach( $nodes as $node )
    {
        // Add New Branch if not Termination
        if( !isset( $lastNode[ $node ] ) && $node != end($nodes) )
            $lastNode[ $node ] = array();
        // Recursive Addressing
        $lastNode = &$lastNode[ $node ];
    }        
 }

它生成树的var_dump()(与我的数据库中的数据匹配):

array (size=3)
  1 => 
    array (size=1)
      4 => null
  2 => 
    array (size=2)
      5 => 
        array (size=1)
          7 => &null
      6 => null
  3 => null

第三个深度向下将终端节点设置为"&null",而不仅仅是"null"。我该怎么解决这个问题?

它只发生在数组中的最后一个项上,因此修复它的一种方法是在$categories的末尾添加一个NULL值,然后用array_filter:将其删除

$categories = [
    (object)['NodePath' => '1'],
    (object)['NodePath' => '1:4'],
    (object)['NodePath' => '2'],
    (object)['NodePath' => '2:5:7'],
    (object)['NodePath' => '2:6'],
    (object)['NodePath' => '3'],
    (object)['NodePath' => '2:5'],
    (object)['NodePath' => '3:1']
];
$tree = array();
$categories[] = (object)array('NodePath' => NULL);
foreach( $categories as $category ){
   $nodes = explode( ":", $category->NodePath );
   $lastNode = &$tree;
   foreach( $nodes as $node ){
       // Add New Branch if not Termination
       if( !isset( $lastNode[ $node ] ) && $node != end($nodes) ){
           $lastNode[ $node ] = array();
       }
       // Recursive Addressing
       $lastNode = &$lastNode[ $node ];
   }        
}
$tree = array_filter($tree);
var_dump($tree);

这是一个转储,它在最后一个值之前有&。我还尝试重新排列categories数组中的元素,结果也一样。

array(3) { [1]=> array(1) { [4]=> NULL } [2]=> array(2) { [5]=> array(1) { [7]=> NULL } [6]=> NULL } [3]=> array(1) { [1]=> NULL } } 
<?php

function builTree($categories){
    $tree = array();
    foreach($categories as $category){
        $path = explode( ":", $category->NodePath );
        $lastNode = &$tree;
        for($deep=0;$deep<count($path);$deep++){
             if(!is_array($lastNode[$path[$deep]])) {
                 if($deep==count($path)-1) { $lastNode[$path[$deep]] = null;}
                 else {$lastNode[$path[$deep]] = array(); $lastNode = &$lastNode[$path[$deep]];}
             } else {$lastNode = &$lastNode[$path[$deep]];}
        }
    }
    return $tree;
}

echo "<pre>";
// works with full tree given
$categories = [
    (object)['NodePath' => '1'],
    (object)['NodePath' => '1:4'],
    (object)['NodePath' => '2'],
    (object)['NodePath' => '2:5:7:90:23'],
    (object)['NodePath' => '2:6'],
    (object)['NodePath' => '3'],
    (object)['NodePath' => '2:5'],
    (object)['NodePath' => '3:1']     // even works with loop paths
];
print_r(builTree($categories));

// works even if just leafs are given
$categories = [
(object)['NodePath' => '2:5:7:90:23'],
(object)['NodePath' => '2:5:7:66:21']
];
print_r(builTree($categories));