php 二维数组以树形输出(转)

时间:2023-03-08 15:23:14
php 二维数组以树形输出(转)

<?php

/**
* @author Skyline
* @copyright 2011
*/

$cate = array(
1=>array(
'id'=>1,
'pid'=>0,
'name'=>'News_1'
),
2=>array(
'id'=>2,
'pid'=>1,
'name'=>'News_12'
),
7=>array(
'id'=>7,
'pid'=>1,
'name'=>'News_17'
),
3=>array(
'id'=>3,
'pid'=>2,
'name'=>'News_123'
),
8=>array(
'id'=>8,
'pid'=>7,
'name'=>'News_178'
),
4=>array(
'id'=>4,
'pid'=>0,
'name'=>'News_4'
),
5=>array(
'id'=>5,
'pid'=>4,
'name'=>'News_45'
),
6=>array(
'id'=>6,
'pid'=>5,
'name'=>'News_456'
)
);

function getchild($pid,$arr){
$sa = $newarr = array();
if(is_array($arr)){
foreach($arr as $id => $sa){
if($sa['pid']== $pid) $newarr[$id]=$sa;
}
}
return $newarr ? $newarr :false;
}

function get_tree($pid,$arr,$num){
global $str;
$child = getchild($pid,$arr);

if(is_array($child)){

$total = count($child);
foreach($child as $id => $sa){
$pstr ='|-';
for($i =0; $i <= $num; $i ++){
$pstr = $pstr .'----';
}
$str = $str . $pstr . $sa['name']."-----$num "." <br>";
$num++;
get_tree($sa['id'],$arr,$num);
$num--;
}
}else{return;}
}

get_tree(0,$cate,0);
echo $str;

?>