php 读取树形结构的完整代码

前端之家收集整理的这篇文章主要介绍了php 读取树形结构的完整代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
经测试代码如下:

/**
 *  从数组转换,操作无限分类数组.
 *  数组格式,array(array('cid','pid','val'),array('cid','val'));
 *
 * @param 
 * @author 编程之家 jb51.cc jb51.cc
 **/
class tree_array {
 var $data = array();
 var $child = array();
 var $layer = array();
 var $parent = array();
 // $array,被操纵的数组,$cid 分类 id 的key. $pid 父分类 id 的key. $value 数据的 key
 function tree_array($array = array(),$cid = 'cid',$pid = 'pid',$value = null) {
  if(!is_array($array)) return false;
  foreach($array as $v) {
   if(isset($v[$value])) {
    $this->setNode($v[$cid],$v[$pid],$v[$value]);
   }
   else
   {
    $this->setNode($v[$cid],$v);
   }
  }
 }
 function setNode($id,$parent,$value){
  $parent = $parent ? $parent : 0;
  $this->data[$id] = $value;
  // if(!isset($this->child[$id])) $this->child[$id] = array();
  if(!isset($this->child[$parent])) $this->child[$parent] = array();
  $this->child[$parent][] = $id;
  $this->parent[$id] = $parent;
 }
 function getValue($id) {
  if(!isset($this->data[$id])) return false;
  return $this->data[$id];
 }
 function getLayer($id,$space = false) {
  if(!isset($this->parent[$id])) return false;
  $layer = count($this->getParents($id)) + 1;
  return $space ? str_repeat($space,$layer) : $layer;
 }
 function getTreeList(&$tree,$root= 0,$space=null) {
  if(!isset($this->child[$root])) return false;
  foreach($this->child[$root] as $key=>$id) {
   if($space) {
    $tree[$id] = $this->getLayer($id,$space) . $this->data[$id];
   }
   else
   {
    $tree[$id] = $this->data[$id];
   }
   if(isset($this->child[$id])) $this->getTreeList($tree,$id,$space);
  }
 }
 function getParent($id) {
  if(!isset($this->parent[$id])) return false;
  $tid = $this->parent[$id];
        if(!$tid) return 0;
  return array($tid => $this->data[$tid]);
 }
 function getParents($id) {
  if(!isset($this->parent[$id])) return false;
  $parents = array();
  while($this->parent[$id]){
   $id = $this->parent[$id];
   $parents[$id] = $this->data[$id];
  }
  return $parents;
 }
 function getChild($id) {
  if(!isset($this->child[$id])) return false;
  $array = array();
  foreach($this->child[$id] as $v) {
   $array[$v] = $this->data[$v];
  }
  return $array;
 }
 function getChilds($id = 0) {
  if(!isset($this->child[$id])) return false;
  $child = array();
  $this->getTreeList($child,$id);
  return $child;
 }
 function html_options($id = 0,$space=' ',$layer=0) {
  static $layer;
  if(!isset($this->child[$id])) return false;
  $tree = array();
  foreach($this->child[$id] as $key=>$id) {
   if($space) {
    $tree[$id] =(str_repeat($space,$layer)) . $this->data[$id];
   }
   else
   {
    $tree[$id] = $this->data[$id];
   }
   if(isset($this->child[$id])) {
    $layer++;
    $tree += $this->html_options($id,$space,$layer);
    $layer--;
   }
  }
  return $tree;
 }
}

/***   代码来自编程之家 jb51.cc(jb51.cc)   ***/
原文链接:https://www.f2er.com/php/529059.html

猜你在找的PHP相关文章