//测试数据 $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