PHP unlimited classification tree data formatting

WBOY
Release: 2016-07-25 09:06:37
Original
970 people have browsed it
Simplicity is the way to go....
  1. function genTree($items,$id='id',$pid='pid',$son = 'children'){
  2. $tree = array(); //Formatted tree
  3. $tmpMap = array(); //Temporary flat data
  4. foreach ($items as $item) {
  5. $tmpMap[$item[$id]] = $item;
  6. }
  7. foreach ($items as $item) {
  8. if (isset($tmpMap[$item[$pid]])) {
  9. $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
  10. } else {
  11. $tree[] = &$tmpMap[$item[$id]];
  12. }
  13. }
  14. unset($tmpMap);
  15. return $tree;
  16. }
  17. $items1 = array(
  18. array('id' = > 1, 'pid' => 0, 'name' => 'Level 11' ),
  19. array('id' => 11, 'pid' => 0, 'name' => 'Level 12' ),
  20. array('id' => 2, 'pid' => 1, 'name' => 'Level 21' ),
  21. array('id' => 10, 'pid' => 11, 'name' => 'Level 22' ),
  22. array('id' => 3, 'pid' => 1, 'name' => 'Level 23 ' ),
  23. array('id' => 12, 'pid' => 11, 'name' => 'Level 24' ),
  24. array('id' => 9, 'pid' = > 1, 'name' => 'Level 25' ),
  25. array('id' => 14, 'pid' => 1, 'name' => 'Level 26' ),
  26. array('id' => 4, 'pid' => 9, 'name' => 'Level 31' ),
  27. array('id' => 6, 'pid' => 9, 'name' => 'Level 3 32' ),
  28. array('id' => 7, 'pid' => 4, 'name' => 'Level 4 41' ),
  29. array('id ' => 8, 'pid' => 4, 'name' => 'Level 4 42' ),
  30. array('id' => 5, 'pid' => 4, 'name' = > 'Level 4 43' ),
  31. array('id' => 13, 'pid' => 4, 'name' => 'Level 4 44' ),
  32. array('id' => 15, 'pid' => 8, 'name' => 'Level 5 51' ),
  33. array('id' => 16, 'pid' => 8, 'name' => 'Five Level 52' ),
  34. array('id' => 17, 'pid' => 8, 'name' => 'Level 53' ),
  35. array('id' => 18, 'pid ' => 16, 'name' => 'Level 6 64' ),
  36. );
  37. var_dump(genTree($items1));
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