Unlimited categories, query data from database, recursively perform custom sorting in arrays
Release: 2016-07-25 09:02:08
Original
953 people have browsed it
Unlimited classification, querying data from the database, and recursively performing custom sorting in the array. I also realized that there are many shortcomings and they are not handled well. There may be a better way. Let's discuss it together. It's more than 100 lines. Not all
- class Tree{
- protected $arr = array(); //Sort array
- protected $info = array(); //Storage error information
- protected $tree = array(); //Storage generated class array
- protected $flag = true; //Flag bit
-
- public function __construct()
- {
-
- }
- //Get data
- public function data($fid,$arr)
- {
- $this->checkArr($arr );
- $this->checking();
- $this->chindAll($fid);
- return $this->tree;
- }
-
- //Judge whether the parameters meet the requirements
- protected function checkArr($ val)
- {
- static $num = 0;
- if(is_array($val)){
- foreach($val as $Varr){
- $this->isKeyVal('id', $Varr, $num);
- $this->isKeyVal('parentid', $Varr, $num);
- $this->isKeyVal('name', $Varr, $num);
- $num++;
- }
- }
- $this- >arr = $val;
- }
- //Whether the stored id is an array
- protected function checkNum($val)
- {
- if(!is_numeric($val)){
- $this->info[] = ' The incoming parameter '.$val.' is not a numerical value';
- $this->flag = false;
- $this->checking();
- }
- }
- //Verification, output error message
- protected function checking( ){
- if(!$this->flag){
- echo '
';
- var_dump($this->info);
- exit();
- }
- }
-
- //Judge array key Whether it exists and whether it has a value
- protected function isKeyVal($key, $arr, $num)
- {
- if(!array_key_exists($key, $arr))
- {
- $this->info[] = $num. 'Array key'.$key.'does not exist';
- $this->flag = false;
-
- }
- }
-
- //Get the son
- public function getChind($fid)
- {
- static $num = 0 ;
- $arr = array();
- $this->checkNum($fid);
- foreach($this->arr as $key=>$row){
- if( $row['parentid'] == $fid){
- $arr[] = $row;
- unset($this->arr[$key]);
- }
- }
- if(!empty($arr)){
- $num++;
- return $this->sortArr($arr);
- }else{
- return null;
- }
- }
-
- //Get my son and grandson
- public function chindAll($fid,$input=null)
- {
- static $ n =0;
- $n++;
- $arr = $this->getChind($fid);
- if(!empty($arr)){
- $count = count($arr);
- if(empty($ input)){
- for($i=0; $i<$count ;$i++){
- $this->tree[$i] = $arr[$i];
- }
Copy code
|
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31