在我的 MYSQL 数据库中,我有 2 个表:
+-------------------+ +---------------------------------+
| tags | | relationships |
+----+--------------+ +---------+---------+------+------+
| id | tag | | x_table | y_table | x_id | y_id |
+----+--------------+ +---------+---------+------+------+
| 1 | parent 1 | | tags | tags | 1 | 2 |
| 2 | child 1 | | tags | tags | 1 | 3 |
| 3 | child 2 | | tags | tags | 3 | 4 |
| 4 | grandchild 1 | +---------+---------+------+------+
+----+--------------+
我需要将这些关系加载到一个多维数组中。孩子的数量可以改变,深度可以改变。每个关系树的深度也不同。
现在我读到递归函数比 PHP 等解释语言的循环慢,并且想知道是否甚至可以用循环编写它,如果是这样,它是否会比使用递归更快且资源消耗更少功能?
多维数组的结构应该如下:
array(
'id' => $id_from_db,
'tag' => $tag_from_db,
'children' => array( /* Just like parent array or false/NULL */ )
)
编辑: 这里的 SQLfiddle
编辑:我创建了递归函数来实现这一点:
private function get_tags($id = false){
global $pdo;
$tags = array();
if(!$id)
$info = $pdo->query("SELECT DISTINCT
t.id,
t.tag
FROM tags t
JOIN relationships r
ON r.x_table = 'tags'
AND r.y_table = 'tags'
AND t.id NOT IN ( SELECT rb.y_id FROM relationships rb WHERE x_table = 'tags' AND y_table = 'tags' )
ORDER BY t.tag");
else
$info = $pdo->query("SELECT DISTINCT
t.id,
t.tag
FROM tags t
JOIN relationships r
ON r.x_table = 'tags'
AND r.y_table = 'tags'
AND r.x_id = " .(int)$id."
AND r.y_id = t.id
ORDER BY t.tag");
while($tag = $info->fetch(PDO::FETCH_ASSOC))
$tags[] = array('tag' => $tag['tag'], 'children' => $this->get_tags($tag['id']) );
if(!count($tags))
return false;
return $tags;
}