Home >Backend Development >PHP Tutorial >Cleverly use PHP references to achieve unlimited classification and output hierarchical arrays

Cleverly use PHP references to achieve unlimited classification and output hierarchical arrays

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 08:50:061096browse
Data table fields, id, parentid.
Parent category parentid=0, subcategory parentid=parentid.
  1. function getDataTree($rows, $id='id',$pid = 'parentid',$child = 'child',$root=0) { $tree = array(); // Tree
  2. if( is_array($rows)){
  3. $array = array();
  4. foreach ($rows as $key=>$item){
  5. $array[$item[$id]] =& $rows[$key];
  6. }
  7. foreach($rows as $key=>$item){
  8. $parentId = $item[$pid];
  9. if($root == $parentId){
  10. $tree[] =&$rows[$ key];
  11. }else{
  12. if(isset($array[$parentId])){
  13. $parent =&$array[$parentId];
  14. $parent[$child][]=&$rows[$key] ;
  15. }
  16. }
  17. }
  18. }
  19. return $tree;
  20. }
Copy code


Statement:
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