php树型类实例

yipeiwu_com5年前PHP代码库

本文实例讲述了php树型类。分享给大家供大家参考。具体分析如下:

该实例原理简单,学过数据结构的一看就明白是什么道理了,不过今天在使用时数据中出现了子节点id(71)小于父节点id(104).导致部分子节点没被存储入数组,修改了一下,实例代码如下:

复制代码 代码如下:
<?php
class tree
{
    var $data = array();
    var $child = array(-1=>array());
    var $layer = array(-1=>-1);
    var $parent = array();
    var $num = array();
 
    function setnode($id, $parent, $value,$num=0)
    {
        $parent = $parent ? $parent : 0;
 
        $this->data[$id]  = $value;
        $this->num[$id]      = $num;
        if (!isset($this->child[$id])) $this->child[$id] = array();
        $this->child[$parent][] = $id;
        $this->parent[$id]  = $parent;
 
        if (!isset($this->layer[$parent]) && $parent == 0)
        {
           $this->layer[$id] = 0;
        }
        else
        {
            $this->layer[$id] = $this->layer[$parent] + 1;
        }
    }
 
    function getlist(&$tree, $root= 0)
    {
        foreach ($this->child[$root] as $key=>$id)
        {
            $tree[] = $id;
            if($this->child[$id]) $this->getlist($tree, $id);
        }
    }
 
    function getvalue($id)
    {
   if($this->layer[$id]==0)
   {
    return $this->data[$id];
   }
   else
   {
    return $leftmar.$this->data[$id];
   }
    }
 
    function getnum($id)
    {
   return $this->num[$id];
    }
 
    function getbitvalue($id)
    {
   return $this->data[$id];
    }
 
    function getlayer($id, $space = false)
    {
        return $space ? str_repeat($space, $this->layer[$id]) : $this->layer[$id];
    }
 
    function getparent($id)
    {
        return $this->parent[$id];
    }
 
    function getparents($id)
    {
        while ($this->parent[$id] != -1)
        {
            $id = $parent[$this->layer[$id]] = $this->parent[$id];
        }
 
        ksort($parent);
        reset($parent);
 
        return $parent;
    }
 
    function getchild($id)
    {
        return $this->child[$id];
    }
 
    function getchilds($id = 0)
    {
        $child = array($id);
        $this->getlist($child, $id);
 
        return $child;
    }
 
    function printdata()
    {
        return $this->layer;
    }
}
?>

希望本文所述对大家的PHP程序设计有所帮助。

相关文章

Apache下禁止php文件被直接访问的解决方案

Apache下禁止php文件被直接访问的解决方案

  一开始,我想在重写规则里直接禁止php后缀的URL被访问。但后来发现重写规则是递归调用的,如果在重写规则里直接禁止php,那么重写到php文件的规则也会失效。RewriteEngin...

PHP 7安装调试工具Xdebug扩展的方法教程

PHP 7安装调试工具Xdebug扩展的方法教程

前言 说到PHP代码调试,对于有经验的PHPer,通过echo、print_r、var_dump函数,或PHP开发工具zend studio、editplus可解决大部分问题,但是对于P...

PHP 反向排序和随机排序代码

array_reverse()函数与shuffle()函数介绍 array_reverse() array array_reverse(array)array_reverse()函数传入...

附件名前加网站名

附件下载 时附件名前加网站名,也就是说下载到本机时,文件名上就加了网站名 你注册下载时就出现【宜配屋www.yipeiwu.com】论坛下载-后名是附件名 1 inc...

php配置php-fpm启动参数及配置详解

约定几个目录 /usr/local/php/sbin/php-fpm/usr/local/php/etc/php-fpm.conf/usr/local/php/etc/php.ini一,...