$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