从具有类别id的平面阵列形成树

时间:2012-05-02 10:19:58

标签: php arrays recursion tree

我有一大块遗留数据,其格式看起来像这样:

Name         | Bid      
-----------------------
Animal       | 1
Canine       | 11
Dog          | 111
Bulldog      | 1111
Wolf         | 112
Hyena        | 113
Feline       | 12
Cat          | 121
Lion         | 122

Bid字段是一个描述类别关系的字符串,这意味着数据结构如下所示:

Animal
  Canine
    Dog
      Bulldog
    Wolf
    Hyena
  Feline
    Cat
    Lion

从数据构建数组树的最佳方法是什么?源数据是一维的,这使得难以使用递归。我一直试图想出循环的逻辑一段时间,但还没有找到合理的解决方案。

1 个答案:

答案 0 :(得分:1)

$data = array(
  array('Name' => 'Animal',  'Bid' => '1'  ),
  array('Name' => 'Canine',  'Bid' => '11'  ),
  array('Name' => 'Dog',     'Bid' => '111' ),
  array('Name' => 'Bulldog', 'Bid' => '1111'),
  array('Name' => 'Wolf',    'Bid' => '112' ),
  array('Name' => 'Hyena',   'Bid' => '113' ),
  array('Name' => 'Feline',  'Bid' => '12'  ),
  array('Name' => 'Cat',     'Bid' => '121' ),
  array('Name' => 'Lion',    'Bid' => '122' ),
);


$struct = array(
  'children' => array()
);

foreach ($data as $entry) {
  $parent =& $struct;

  foreach (str_split($entry['Bid'], 1) as $val) {
    if (!isset($parent['children'][$val])) {
      // if not, we create an empty entry
      $parent['children'][$val] = array(
        'entry' => array(),  // no content
        'children' => array()  // no children
      );
    }

    $parent =& $parent['children'][$val];
  }

  $parent['entry'] = $entry;
}

print_r($struct);

并使用:

function render($elements, $depth = 0) {
  foreach ($elements as $element) {
    printf("%s%s\n", str_repeat(' ', $depth * 2), $element['entry']['Name']);
    render($element['children'], $depth + 1);
  }
}

render($struct['children']);

你会得到:

Animal
  Canine
    Dog
      Bulldog
    Wolf
    Hyena
  Feline
    Cat
    Lion