php 把返回的数据集转换成数组树
如
$old = array(
array('id'=>1,'pid'=>0,'name'=>'第一个' ),
array('id'=>2,'pid'=>1,'name'=>'第二个' ) ,
array('id'=>3,'pid'=>2,'name'=>'第三个'),
);
print_r(list_to_tree($old,'id','pid','_child'));
输出如下
$old = array(
array(
'id'=>1,
'pid'=>0,
'name'=>'第一个',
'_child'=>array(
'id'=>2,
'pid'=>1,
'name'=>'第二个'
'_child'=>array('id'=>3,'pid'=>2,'name'=>'第三个'),
),
) ,
);
/**
* 把返回的数据集转换成Tree
* @access public
* @param array $list 要转换的数据集
* @param string $pid parent标记字段
* @param string $level level标记字段
* @return array
*/
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
// 创建Tree
$tree = array();
if(is_array($list)) {
// 创建基于主键的数组引用
$refer = array();
foreach ($list as $key => $data) {
$refer[$data[$pk]] =& $list[$key];
}
foreach ($list as $key => $data) {
// 判断是否存在parent
$parentId = $data[$pid];
if ($root == $parentId) {
$tree[] =& $list[$key];
}else{
if (isset($refer[$parentId])) {
$parent =& $refer[$parentId];
$parent[$child][] =& $list[$key];
}
}
}
}
return $tree;
}
//该片段来自于http://outofmemory.cn






