Home  >  Article  >  Backend Development  >  Tree Algorithm_PHP Tutorial

Tree Algorithm_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:28:02730browse

//测试数据 $ar = array( array(id=>1,pid=>0), array(id=>2,pid=>0), array(id=>3,pid=>2), array(id=>4,pid=>0), array(id=>5,pid=>3), array(id=>6,pid=>1), array(id=>7,pid=>1), array(id=>8,pid=>6 ), array(id=>9,pid=>7), array(id=>10,pid=>9) ); //Sort function function cmd($a,$b) { if($a[pid] ==$b[pid]) return 0; return $a[pid]>$b[pid]?1:-1; } //Sort, in order to avoid the parent node appearing behind the child node in the data, this situation is It often happens after modifying data multiple times //The purpose of sorting is to prevent the confusion caused by this situation uasort($ar,cmd); //Define the target array $d = array(); //Define the index array for Record the position of the node in the target array $ind = array(); foreach($ar as $v) { $v[child] = array(); //Attach a child item to each node if($v[pid] == 0) { $i = count($d); $d[$i] = $v; $ind[$v[id]] =& $d[$i]; }else { $i = count( $ind[$v[pid]][child]); $ind[$v[pid]][child][$i] = $v; $ind[$v[id]] =& $ind[$v [pid]][child][$i]; } } //Check results print_r($d); ?> Algorithm features: Using the B+ tree concept, a tree array can be generated with only one cycle

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/531826.htmlTechArticle1,pid=>0), array(id=>2,pid=>0), array(id =>3,pid=>2), array(id=>4,pid=>0), array(id=>5,pid=>3), array(id=>6,pid=>1), array (id=>7,pid=>1), array(id=>8,pid=>6), array(id=>9,pid=>7), a...
Statement:
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