Convert the returned data set into an array tree

WBOY
Release: 2016-07-25 09:01:28
Original
1384 people have browsed it
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' ),
),
) ,

);
  1. /**
  2. * Convert the returned data set into a Tree
  3. * @access public
  4. * @param array $list The data set to be converted
  5. * @param string $pid parent tag field
  6. * @param string $level level tag field
  7. * @ return array
  8. */
  9. function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
  10. // Create Tree
  11. $tree = array();
  12. if(is_array($list)) {
  13. // Create an array reference based on the primary key
  14. $refer = array();
  15. foreach ($list as $key => $data) {
  16. $refer[$data[$pk]] =& $list[$key];
  17. }
  18. foreach ($list as $key => $data) {
  19. // Determine whether parent exists
  20. $parentId = $ data[$pid];
  21. if ($root == $parentId) {
  22. $tree[] =& $list[$key];
  23. }else{
  24. if (isset($refer[$parentId])) {
  25. $parent =& $refer[$parentId];
  26. $parent[$child][] =& $list[$key];
  27. }
  28. }
  29. }
  30. }
  31. return $tree;
  32. }
Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!