Get the path relationship of infinite categories of left and right values

WBOY
Release: 2016-07-25 08:50:57
Original
880 people have browsed it
Recently, I need something that can display something like
1 > 2
1 > 2 > 3
1 > 2 > 3 > 4
. I don’t know the algorithm, so I just took a lot of detours. Of course, I hope you have a better way. Tucao is welcome.
  1. public function getPaths($nodes)
  2. {
  3. $levels = $paths = array();
  4. // Reorganize array levels
  5. foreach ($nodes as $id => $node)
  6. {
  7. $levels[ $node['level']][$id] = $node;
  8. }
  9. for ($i = 0; $i < count($levels); $i++)
  10. {
  11. if (is_array($levels[$ i]))
  12. {
  13. foreach ($levels[$i] as $level)
  14. {
  15. $id = $level['id'];
  16. $parent_id = $level['parent_id'];
  17. $parent = $ paths[$parent_id];
  18. // There is a parent and appended to the current node
  19. if ($parent)
  20. {
  21. $paths[$id] = $parent;
  22. $paths[$id][] = $level[ 'id'];
  23. }
  24. else
  25. {
  26. $paths[$id][] = $level['id'];
  27. }
  28. }
  29. }
  30. }
  31. return $paths;
  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!