所以,我的问题是,我想构建这两个表的树:
Parent table:
+-------+---------------+
| pr_id | parent_name |
+-------+---------------+
| 1 | p |
| 2 | p_0 |
| 3 | p_0_1 |
| 4 | q |
+-------+---------------+
Child table:
+-------+---------------+---------------------------+
| ch_id | pr_id | child_name |
+-------+---------------+---------------------------+
| 1 | 1 | p_0 |
| 2 | 1 | p_1 |
| 3 | 2 | p_0_0 |
| 4 | 2 | p_0_1 |
| 5 | 3 | p_0_1_0 |
| 6 | 3 | p_0_1_1 |
| 7 | 4 | q_0 |
| 8 | 4 | q_1 |
+-------+---------------+---------------------------+
树应该看起来像:
任何人都可以通过递归解决方案帮助我吗?
答案 0 :(得分:30)
您不需要在数据库中创建2个表,只需从一个表中维护它就像下面一样
+-------+---------------+---------------------------+
| id | parent_id | title |
+-------+---------------+---------------------------+
| 1 | 0 | Parent Page |
| 2 | 1 | Sub Page |
| 3 | 2 | Sub Sub Page |
| 4 | 0 | Another Parent Page |
+-------+---------------+---------------------------+
生成的数组将类似于
Array
(
[0] => Array
(
[id] => 1
[parent_id] => 0
[title] => Parent Page
[children] => Array
(
[0] => Array
(
[id] => 2
[parent_id] => 1
[title] => Sub Page
[children] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 1
[title] => Sub Sub Page
)
)
)
)
)
[1] => Array
(
[id] => 4
[parent_id] => 0
[title] => Another Parent Page
)
)
你需要使用下面的递归函数来实现它
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($rows);
算法非常简单: