无限分类,从数据库查询数据 在数组中递归进行自定义排序

WBOY
Libérer: 2016-07-25 09:02:08
original
871 Les gens l'ont consulté
无限分类,从数据库查询数据 在数组中递归进行自定义排序,其中也意识到挺多不足,处理得不好,可能有更好办法,大家一起交流 超过100行了。放不全
  1. class Tree{
  2. protected $arr = array(); //排序数组
  3. protected $info = array(); //存放错误信息
  4. protected $tree = array(); //存放生成类数组
  5. protected $flag = true; //标志位
  6. public function __construct()
  7. {
  8. }
  9. //得到数据
  10. public function data($fid,$arr)
  11. {
  12. $this->checkArr($arr);
  13. $this->checking();
  14. $this->chindAll($fid);
  15. return $this->tree;
  16. }
  17. //判断参数是否符合要求
  18. protected function checkArr($val)
  19. {
  20. static $num = 0;
  21. if(is_array($val)){
  22. foreach($val as $Varr){
  23. $this->isKeyVal('id', $Varr, $num);
  24. $this->isKeyVal('parentid', $Varr, $num);
  25. $this->isKeyVal('name', $Varr, $num);
  26. $num++;
  27. }
  28. }
  29. $this->arr = $val;
  30. }
  31. //存入id是否是数组
  32. protected function checkNum($val)
  33. {
  34. if(!is_numeric($val)){
  35. $this->info[] = '传入参数'.$val.'不是数值';
  36. $this->flag = false;
  37. $this->checking();
  38. }
  39. }
  40. //验证,输出错误信息
  41. protected function checking(){
  42. if(!$this->flag){
  43. echo '
    ';
    Copier après la connexion
  44. var_dump($this->info);
  45. exit();
  46. }
  47. }
  48. //判断数组键是否存在,是否有值
  49. protected function isKeyVal($key, $arr, $num)
  50. {
  51. if(!array_key_exists($key, $arr))
  52. {
  53. $this->info[] = $num.'数组键'.$key.'不存在';
  54. $this->flag = false;
  55. }
  56. }
  57. //获得儿子
  58. public function getChind($fid)
  59. {
  60. static $num = 0;
  61. $arr = array();
  62. $this->checkNum($fid);
  63. foreach($this->arr as $key=>$row){
  64. if( $row['parentid'] == $fid){
  65. $arr[] = $row;
  66. unset($this->arr[$key]);
  67. }
  68. }
  69. if(!empty($arr)){
  70. $num++;
  71. return $this->sortArr($arr);
  72. }else{
  73. return null;
  74. }
  75. }
  76. //获取本人儿子孙子
  77. public function chindAll($fid,$input=null)
  78. {
  79. static $n =0;
  80. $n++;
  81. $arr = $this->getChind($fid);
  82. if(!empty($arr)){
  83. $count = count($arr);
  84. if(empty($input)){
  85. for($i=0; $i $this->tree[$i] = $arr[$i];
  86. }
复制代码


source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!