PHP非递归实现无限级分类

有些系统中,要求对信息栏目进行无限级的分类,以增强系统的灵活性。那么PHP是如何实现无限级分类的呢?常用办法是使用递归,把所有分级查询出来,但是在数据量特别多的时候,多次查询,就会使得效率变得低下,以下是非递归实现无线分类:

<?phpclass Tree
{
public $data = array();
public $cateArray = array();

function __construct()
{
$tree_data = array(
array('id' => 1, 'parent_id' => 0, 'name' => '中国'),
array('id' => 2, 'parent_id' => 1, 'name' => '广东'),
array('id' => 3, 'parent_id' => 1, 'name' => '江西'),
array('id' => 4, 'parent_id' => 1, 'name' => '湖南'),
array('id' => 5, 'parent_id' => 2, 'name' => '深圳'),
array('id' => 6, 'parent_id' => 2, 'name' => '广州'),
array('id' => 7, 'parent_id' => 3, 'name' => '赣州'),
array('id' => 8, 'parent_id' => 3, 'name' => '南昌'),
array('id' => 9, 'parent_id' => 4, 'name' => '长沙'),
);

foreach ($tree_data as $data) {
$this->setNode($data['id'], $data['parent_id'], $data);
}
}

function Tree()
{

}

function setNode($id, $parent, $value)
{
$parent = $parent ? $parent : 0;
$this->data[$id] = $value;
$this->cateArray[$id] = $parent;
}

function getChildsTree($id = 0)
{
$childs = array();
foreach ($this->cateArray as $child => $parent) {
if ($parent == $id) {
$childs[$child] = $this->getChildsTree($child);
}
}
return $childs;
}

function getParentsTree($id = 0)
{
$parents = array();
foreach ($this->cateArray as $child => $parent) {
if ($child == $id) {
$parents[$parent] = $this->getParentsTree($parent);
}
}
return $parents;
}

function getChilds($id = 0)
{
$childArray = array();
$childs = $this->getChild($id);
foreach ($childs as $child) {
$childArray[] = $child;
$childArray = array_merge($childArray, $this->getChilds($child));
}
return $childArray;
}

function getChild($id)
{
$childs = array();
foreach ($this->cateArray as $child => $parent) {
if ($parent == $id) {
$childs[$child] = $child;
}
}
return $childs;
}

function getParents($id)
{
$parentArray = array();
$parents = $this->getParent($id);
foreach ($parents as $parent) {
$parentArray[] = $parent;
$parentArray = array_merge($parentArray, $this->getParents($parent));
}
return $parentArray;
}

function getParent($id)
{
$parents = array();
foreach ($this->cateArray as $child => $parent) {
if ($child == $id) {
$parents[$parent] = $parent;
}
}
return $parents;
}

//单线获取父节点
function getNodeLever($id)
{
$parents = array();
if (key_exists($this->cateArray[$id], $this->cateArray)) {
$parents[] = $this->cateArray[$id];
$parents = array_merge($parents, $this->getNodeLever($this->cateArray[$id]));
}
return $parents;
}

function getLayer($id, $preStr = '|-')
{
return str_repeat($preStr, count($this->getNodeLever($id)));
}

function getValue($id)
{
return $this->data[$id];
}
}

打赏此文

如果您觉得本站的内容对您有所帮助,您可以扫描下面的二维码小额支付请我喝杯茶,感谢!打赏记录
支付宝
微信
承诺:凡打赏捐助的朋友,留言备注自己的邮箱,在打赏捐助时间点的6个月内,本站会每周邮件推送原创专业技术博文,供大家学习和参考!

留下评论

All fields marked (*) are required