Home Backend Development PHP Tutorial Thinkphp的list_to_tree 实现无限级归类列出所有节点

Thinkphp的list_to_tree 实现无限级归类列出所有节点

Jun 13, 2016 pm 12:01 PM
array list tree

Thinkphp的list_to_tree 实现无限级分类列出所有节点
list_to_tree 使用起来十分方便,详细可查看手册。因为我在用的时候需要同时列出所有节点,所以写了一个递归函数,拿出来供大家参考。

public function index(){    Load('extend');            //加载扩展方法    $Category=D('Category');    $list=$Category->order('sort desc')->select();//实现同级节点排序    $list=list_to_tree($list,'id','fid'); //详细参数见手册    $list=$this->findChild($list);        dump($list);}protected  function findChild($arr){        static $tree=array();        foreach ($arr as $key=>$val){                $tree[]=$val;                if (isset($val['_child'])){                    $this->findChild($val['_child']);                }                    }    return $tree;}
Copy after login


Copy after login

/** * 把返回的数据集转换成Tree * @access public * @param array $list 要转换的数据集 * @param string $pid parent标记字段 * @param string $level level标记字段 * @return array */function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {    // 创建Tree    $tree = array();    if(is_array($list)) {        // 创建基于主键的数组引用        $refer = array();        foreach ($list as $key => $data) {            $refer[$data[$pk]] =& $list[$key];        }        foreach ($list as $key => $data) {            // 判断是否存在parent            $parentId = $data[$pid];            if ($root == $parentId) {                $tree[] =& $list[$key];            }else{                if (isset($refer[$parentId])) {                    $parent =& $refer[$parentId];                    $parent[$child][] =& $list[$key];                }            }        }    }    return $tree;}/** * 对查询结果集进行排序 * @access public * @param array $list 查询结果 * @param string $field 排序的字段名 * @param array $sortby 排序类型 * asc正向排序 desc逆向排序 nat自然排序 * @return array */function list_sort_by($list,$field, $sortby='asc') {   if(is_array($list)){       $refer = $resultSet = array();       foreach ($list as $i => $data)           $refer[$i] = &$data[$field];       switch ($sortby) {           case 'asc': // 正向排序                asort($refer);                break;           case 'desc':// 逆向排序                arsort($refer);                break;           case 'nat': // 自然排序                natcasesort($refer);                break;       }       foreach ( $refer as $key=> $val)           $resultSet[] = &$list[$key];       return $resultSet;   }   return false;}/** * 在数据列表中搜索 * @access public * @param array $list 数据列表 * @param mixed $condition 查询条件 * 支持 array('name'=>$value) 或者 name=$value * @return array */function list_search($list,$condition) {    if(is_string($condition))        parse_str($condition,$condition);    // 返回的结果集合    $resultSet = array();    foreach ($list as $key=>$data){        $find   =   false;        foreach ($condition as $field=>$value){            if(isset($data[$field])) {                if(0 === strpos($value,'/')) {                    $find   =   preg_match($value,$data[$field]);                }elseif($data[$field]==$value){                    $find = true;                }            }        }        if($find)            $resultSet[]     =   &$list[$key];    }    return $resultSet;}
Copy after login



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement Redis List operation in php How to implement Redis List operation in php May 26, 2023 am 11:51 AM

List operation //Insert a value from the head of the list. $ret=$redis->lPush('city','guangzhou');//Insert a value from the end of the list. $ret=$redis->rPush('city','guangzhou');//Get the elements in the specified range of the list. 0 represents the first element of the list, -1 represents the last element, and -2 represents the penultimate element. $ret=$redis->l

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

How to convert JSONArray to List in Java How to convert JSONArray to List in Java May 04, 2023 pm 05:25 PM

1: JSONArray to ListJSONArray string to List//Initialize JSONArrayJSONArrayarray=newJSONArray();array.add(0,"a");array.add(1,"b");array.add(2,"c") ;Listlist=JSONObject.parseArray(array.toJSONString(),String.class);System.out.println(list.to

Use tree to generate a file directory tree for display Use tree to generate a file directory tree for display Mar 01, 2024 pm 05:46 PM

tree is a command line tool that recursively lists the contents of a directory in a tree format, so that all directories, subdirectories, and files are listed in a hierarchical manner, thereby visually displaying the organizational structure of files and folders. The following are the installation and use methods of tree under Windows and Linux systems. The installation and use of tree under Linux. Installing tree under Linux: aptupdate&&aptinstalltree The following are the common ways of using the tree command. #Display the directory tree under the specified path tree/d/temp #Limit the maximum display depth tree-L3 #Display only directories but not files tree-d #Display including hidden files and directories tr

How to sort a list using List.Sort function in C# How to sort a list using List.Sort function in C# Nov 17, 2023 am 10:58 AM

How to sort a list using the List.Sort function in C# In the C# programming language, we often need to sort the list. The Sort function of the List class is a powerful tool designed for this purpose. This article will introduce how to use the List.Sort function in C# to sort a list, and provide specific code examples to help readers better understand and apply this function. The List.Sort function is a member function of the List class, used to sort elements in the list. This function receives

Simple and clear method to use PHP array_merge_recursive() function Simple and clear method to use PHP array_merge_recursive() function Jun 27, 2023 pm 01:48 PM

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values ​​of the same keys, making the program design more flexible. array_merge

What are the common methods of List in Java basics What are the common methods of List in Java basics May 14, 2023 am 10:16 AM

1. Introduction to List interface List is an ordered collection and a repeatable collection. It inherits the Collection interface. Repeated elements can appear in the List collection, and the element at the specified position can be accessed through the index (subscript). 2. List common methods - voidadd (intindex, Obejctelement) method 1. The voidadd (intindex, Obejctelement) method inserts the element element at the specified position and moves the subsequent element back one element. 2.voidadd(intindex,Obejctelemen

How to convert array to List in Java How to convert array to List in Java Apr 19, 2023 am 09:13 AM

1. The most common way (not necessarily the best) is through Arrays.asList(strArray). After converting the array into List, you cannot add or delete the List, you can only check and modify it, otherwise an exception will be thrown. Key code: Listlist=Arrays.asList(strArray);privatevoidtestArrayCastToListError(){String[]strArray=newString[2];Listlist=Arrays.asList(strArray);//Insert a piece of data into the converted list list.add(" 1&quot

See all articles