like
$old = array(
array('id'=>1,'pid'=>0,'name'=>'first'
),
array('id'=>2,'pid'=>1,'name'=>'second'
)
, array('id'=>3,'pid'=>2,'name'=>'third'),
);
print_r(list_to_tree($old,'id','pid','_child'));
The output is as follows
$old = array(
array( 'id'=>1, 'pid'=>0, 'name'=>'first', '_child'=>array( 'id'=>2, ' pid'=>1, 'name'=>'second' '_child'=>array('id'=>3,'pid'=>2,'name'=>'third' ), ),
)
,
);
- /**
- * Convert the returned data set into a Tree
- * @access public
- * @param array $list The data set to be converted
- * @param string $pid parent tag field
- * @param string $level level tag field
- * @ return array
- */
- function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
- // Create Tree
- $tree = array();
- if(is_array($list)) {
- // Create an array reference based on the primary key
- $refer = array();
- foreach ($list as $key => $data) {
- $refer[$data[$pk]] =& $list[$key];
- }
- foreach ($list as $key => $data) {
- // Determine whether parent exists
- $parentId = $ data[$pid];
- if ($root == $parentId) {
- $tree[] =& $list[$key];
- }else{
- if (isset($refer[$parentId])) {
- $parent =& $refer[$parentId];
- $parent[$child][] =& $list[$key];
- }
- }
- }
- }
- return $tree;
- }
Copy code
|