0

我在数组中有一堆父子ID,如下所示,

 child => parent

 Array
(
  [1] => 0   ===>parent
  [2] => 1
  [4] => 1
  [5] => 4
  [6] => 2
  [7] => 0   ===>parent
  [8] => 2
  [9] => 7
  [10] => 2
  [11] => 2
  [12] => 2
  [17] => 12
  [18] => 17
  [19] => 0    ===>parent
  [20] => 19
  [21] => 20
  [22] => 20
  [23] => 20
)

我的解析树是

                 0->parent
     ____________|___________________________
    |                   |                   |
    1(0's child)        7                   19->0 parent's child[1]->[0],[7]->0,[19]->0
  __|_______            |                   |
  |         |           9                   20
  2         4 (2 & 4 is 1 parent's child)   |
  |         |                            21,22,23
  |         5
  |
 6,8,10,11,12
            |
            17
            |
            18

我想将 0 作为根元素 id,然后检查它的子元素和孙子元素,我的结果数组看起来像,

   $result = Array
        (
        [0] => 1        -->i will use my categoryname here $myarray[1]['categoryname']
        [1] => 1->2      ---> $myarray[1]['categoryname']->$myarray[2]['categoryname']
        [2] => 1->2->6   --->and so on
        [3] => 1->2->8
        [4] => 1->2->10
        [5] => 1->2->11
        [6] => 1->2->12
        [7] => 1->2->12->17
        [8] => 1->2->12->17->18
        [9] => 1->4
        [10] => 1->4->5
        [11] => 7
        [12] => 7->9
        [13] => 19
        [14] => 19->20
        [15] => 19->20->21
        [16] => 19->20->22
        [17] => 19->20->23
       )

类似于将一系列父子关系转化为层次树?这个问题,我的代码是,

  $tree = $this->to_tree($array);
function to_tree($array)
{
$flat = array();
$tree = array();
$abc = array();
  foreach ($array as $child => $parent) 
  {
       if (!isset($flat[$child])) {
        $flat[$child] = array();
       }
       if (!empty($parent)) {
        $flat[$parent][$child] =& $flat[$child];
       } else {

        $tree[$child] =& $flat[$child];
       }
  }
       return $tree;
}

这将打印分层树请帮助我,谢谢。

4

0 回答 0