这里我附上了一张图片,显示了树,我想按照预订顺序旅行
1,2,5,6,3,7,8,4,9,10,11。
我可以在php中使用哪种数据结构来构建这种结构?
答案 0 :(得分:1)
数据结构
简单关联数组将完成工作
array(2) {
["data"]=> int
["children"]=> array()
}
<强> PHP 强>
<?php
function makeTree($data, $children = array()) {
$tree = array();
$tree['data'] = $data;
$tree['children'] = $children;
return $tree;
}
function traverse($tree) {
echo $tree['data'] . "\n";
foreach($tree['children'] as $child) {
traverse($child);
}
}
$root = makeTree(1, array(
makeTree(2, array(makeTree(5), makeTree(6))),
makeTree(3, array(makeTree(7), makeTree(8))),
makeTree(4, array(makeTree(9), makeTree(10), makeTree(11)))
));
traverse($root);
<强>结果强>
1
2
5
6
3
7
8
4
9
10
11