如何存储大型二叉树(深度约为数千)。
我们尝试将其存储在数据库中,使用带有行的表:elem、parent、left_child、right_child,但是处理这个树非常慢(计算、绘制其中一部分)。
您推荐哪种方式?(可以在php中进行计算)。可以将其存储在XML或json(文本文件)中还是在某些矩阵中?
如何存储大型二叉树(深度约为数千)。
我们尝试将其存储在数据库中,使用带有行的表:elem、parent、left_child、right_child,但是处理这个树非常慢(计算、绘制其中一部分)。
您推荐哪种方式?(可以在php中进行计算)。可以将其存储在XML或json(文本文件)中还是在某些矩阵中?
看起来像你建议的那样写入XML会是最好的选择。将其转换为XML,然后在重新加载时再转换回来将会非常简单明了。
2---4---8
/ \ \9
1-- 5---10
\ \11
3---6---12
\ \13
7---14
\15
id parent tree slug name path children
1 0 1 root Root || |5|
2 7 1 child-1 Child 1 |1-5-8-7| |3|
查询深度巨大的树非常容易,因为查询是线性的。
每行中有更多的数据,但这使得查询更快。
例如,您可以通过简单的查询获取整个子树:
$sql = 'SELECT * FROM `'.$this->_table_name.'` WHERE
`path` LIKE "%-:parent-%"
OR `path` LIKE "%|:parent-%"
OR `path` LIKE "%-:parent|%"
OR `path` LIKE "%|:parent|%"';
$result = $this->_db->custom_query($sql, array('parent' => $root->id));
然后通过一个简单的函数构建深度数组:
private function _build_tree(Node $root, $data)
{
$mapped_node = array(
'node' => $root,
'subnodes' => array()
);
if ( !empty($root->children) )
{
foreach( $root->children as $child )
{
if ( array_key_exists($child, $data) )
{
$mapped_node['subnodes'][] = $this->_build_tree($data[$child], $data);
}
}
}
return $mapped_node;
}
注意!当我获取到孩子和路径列时,我将它们分割成数组,以便PHP更好地处理它们。