树形算法_PHP

WBOY
WBOYOriginal
2016-06-01 12:40:00907browse

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

//排序函数
function cmd($a,$b) {
if($a[pid]==$b[pid]) return 0;
return $a[pid]>$b[pid]?1:-1;
}

//排序,为避免数据中父节点在子节点后面出现,这种情况在多次修改数据后经常会发生的
//排序的目的就是防止这种情况造成的混乱
uasort($ar,cmd);

//定义目标数组
$d = array();
//定义索引数组,用于记录节点在目标数组的位置
$ind = array();

foreach($ar as $v) {
$v[child] = array(); //给每个节点附加一个child项
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];
}
}
//检查结果
print_r($d);
?>

算法特点:利用B+树概念,只用一次循环就可生成树形数组
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