Home > php教程 > php手册 > body text

用php和js实现简单的树结构(点击收缩与拉伸)

WBOY
Release: 2016-06-06 19:49:42
Original
1505 people have browsed it

script type=text/javascript src=jquery.js/script script language=javascript type=text/javascript function show(eventName) { $(#eventName).children().toggle(); } /script //树的节点,id是每个节点的唯一标志,pid表示他的父节点 ,name表示节点的


//树的节点,id是每个节点的唯一标志,pid表示他的父节点 ,name表示节点的名称

$result[0] = array('id'=>1,'pid'=>0,'name'=>'公司1',);
$result[1] = array('id'=>2,'pid'=>0,'name'=>'公司2');
$result[2] = array('id'=>3,'pid'=>2,'name'=>'公司2的子公司1');
$result[3] = array('id'=>4,'pid'=>1,'name'=>'公司1的子公司1');
$result[4] = array('id'=>5,'pid'=>2,'name'=>'公司2的子公司2');
$result[5] = array('id'=>6,'pid'=>3,'name'=>'公司2的子公司1的子公司1');
$result[6] = array('id'=>7,'pid'=>3,'name'=>'公司2的子公司1的子公司2');
$result[7] = array('id'=>8,'pid'=>3,'name'=>'公司2的子公司1的子公司3');
$result[8] = array('id'=>9,'pid'=>8,'name'=>'公司2的子公司1的子公司3');
$result[9] = array('id'=>10,'pid'=>9,'name'=>'公司2的子公司1的子公司3');
//简易类
class tree

{

//创建树

   function tree($rs,$idName,$pidName,$nodeName)

    {
        $this->idName    = $idName;//当前节点的id
        $this->pidName    = $pidName;//父节点的id
        $this->nodeName = $nodeName;
        $tree = array();
        foreach((array)$rs as $k=>$v)
        {
            $tree[$v[$pidName]][] = $v;
        }
 
        $this->treeArray = $tree;

    }

//显示树

    function showTree($root,$deep)
    {
        if( $this->treeArray[$root] )
        {
            foreach($this->treeArray[$root] as $k=>$v)
            {
                $t = $v[$this->idName];
                $p = $v[$this->pidName];
                $name=$v[$this->nodeName];

                $str   = str_repeat(" ",$deep*4)."|-".str_repeat("-",$deep);


                $html .=""."{$str}"."{$v[$this->nodeName]}
";
                if($this->treeArray[$t] )

                {


                   $html .="";
                }
                    $html .="
";
            }
        }
        return $html;
    }
}
$tree = new tree($result,'id','pid','name');
echo $tree->showTree(0,0);

?>

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!