0

我有大量的遗留数据,格式有点像这样:

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

从数据构建数组树的最佳方法是什么?源数据是一维的,因此难以使用递归。一段时间以来,我一直在尝试提出循环的逻辑,但还没有提出合理的解决方案。

4

1 回答 1

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
于 2012-05-02T10:53:27.780 回答