无限型将排序的一维数组压制成
程序员文章站
2022-05-28 19:06:08
...
将一维数组压制成为树状结构,例如
1,11,111,1111
1,11,111,1112
1,11,112,1121
压制成为
1
_11
____111
_______1111
_______1112
____112
_______1121
以数组形式存储,最后一级(叶子节点)以一维数组存储,其余各级均以[id=>[],data=>[]]
的格式存储
1,11,111,1111
1,11,111,1112
1,11,112,1121
压制成为
1
_11
____111
_______1111
_______1112
____112
_______1121
以数组形式存储,最后一级(叶子节点)以一维数组存储,其余各级均以[id=>[],data=>[]]
的格式存储
<?php class array_2_tree { //更改方案,使用直接暴力压制下去的方式 private $tree=[]; private $row=[]; private $id_names=false; private $data_names=false; private $row_keys=0; private $row_size=0; function __construct($opt){ $this->init($opt); } private function get_row_value($pos){ if(!$this->row_keys){ $this->row_keys=array_keys($this->row); } return $this->row[$this->row_keys[$pos]]; } function init($opt){ if($opt['id_names'] && is_array($opt['id_names'])){ $this->id_names=$opt['id_names']; } if($opt['data_names'] && is_array($opt['data_names'])){ $this->data_names=$opt['data_names']; } } function pick(&$row){ $this->row=$row; $this->row_size=sizeof($row); $this->smash($this->tree); } function get_tree(){ return $this->tree; } private function smash(&$node,$key_index=0){ $id_name=$this->get_id_name($key_index); $data_name=$this->get_data_name($key_index); if(sizeof($this->row)<$key_index){ return; } if(!sizeof($node)){ if((sizeof($this->row)-1)==($key_index)){ $node[]=$this->get_row_value($key_index); return; }else{ $node[]=[ $id_name=>$this->get_row_value($key_index), $data_name=>[] ]; } $new_node=&$node[0][$data_name]; $node=&$new_node; }else{ $size=sizeof($node); if( ($this->row_size-1) == $key_index){ $node[]=$this->get_row_value($key_index); return; } if( ($node[$size-1][$id_name]) == ($this->get_row_value($key_index)) ){ $next_node=&$node[$size-1][$data_name]; $node=&$next_node; }else{ $node[]=[ $id_name=>$this->get_row_value($key_index), $data_name=>[] ]; $size=sizeof($node); $next_node=&$node[$size-1][$data_name]; $node=&$next_node; } } $this->smash($node,++$key_index); } private function get_id_name($k){ if($this->id_names && $this->id_names[$k]){ return $this->id_names[$k]; }else{ return 'id'; } } private function get_data_name($k){ if($this->data_names && $this->data_names[$k]){ return $this->data_names[$k]; }else{ return 'data'; } } } ?>
$a=[ ['depid'=>1,'uid'=>11,'ymd'=>1,'v'=>1], ['depid'=>1,'uid'=>11,'ymd'=>2,'v'=>2], ['depid'=>1,'uid'=>11,'ymd'=>3,'v'=>3], ['depid'=>1,'uid'=>11,'ymd'=>4,'v'=>4], ['depid'=>1,'uid'=>12,'ymd'=>2,'v'=>5], ['depid'=>1,'uid'=>12,'ymd'=>3,'v'=>6], ['depid'=>1,'uid'=>12,'ymd'=>4,'v'=>7], ['depid'=>1,'uid'=>12,'ymd'=>5,'v'=>8], ['depid'=>2,'uid'=>2,'ymd'=>1,'v'=>9], ['depid'=>2,'uid'=>2,'ymd'=>2,'v'=>10], ['depid'=>2,'uid'=>2,'ymd'=>3,'v'=>11], ['depid'=>2,'uid'=>2,'ymd'=>3,'v'=>12] ]; $r=[]; $t=new array_2_tree(); foreach($a as $k=>$v){ $t->pick($v); } $r=$t->get_tree(); debug($r);
上一篇: PHP 如何获取客户机的每一个请求