gettreenode php,php 树形结构的读取

php 树形结构的读取

<?php // 从数组转换,操作无限分类数组. // 数组格式, array(array('cid', 'pid', 'val'), array('cid', 'pid', 'val')); 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[$pid], $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;

}

}

开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明php 树形结构的读取!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值