PHP递归

<?php
/**
 * Mr.xml
 * 处理无限级分类
 */
class Category{
   /**
    * [递归一维数组]
    * @param  [type] $cate  [传递一个数组$cate]
    * @param  string $html  [标示符]
    * @param  [type] $pid   [所属哪个类]
    * @param  [type] $level [等级]
    * @return [type]        [把数组返回出去]
    */
   static public function unlimitedForLevel($cate, $html = '--', $pid = 0, $level = 0, $str = '♩——'){
      $arr = array();
      foreach ($cate as $v) {
         if($v['pid'] == $pid){
            $v['level'] = $level+1;
            $v['html']  = str_repeat($html, $level);
            if( $level != 0){
              $v['str'] = $str;
            }
            $arr[]      = $v;
            $arr        = array_merge($arr, self::unlimitedForLevel($cate, $html, $v['id'], $level+1));
         }
      }
      return $arr;
   }

   /*递归多维数组*/
   static public function unlimitedForLayer($cate, $name = 'child', $pid = 0)
   {
      $arr = array();
      foreach($cate as $v)
      {
         if($v['pid'] == $pid)
         {
            $v[$name] = self::unlimitedForLayer($cate, $name, $v['id']);
            $arr[] = $v;
         }
      }
      return $arr;      
   }
   
   /*传递一个子分类ID返回所有父级分类*/
   static public function getParents($cate, $id)
   {
      $arr = array();
      foreach($cate as $v)
      {
         if($v['id'] == $id)
         {
            $arr[] =$v;
            $arr = array_merge(self::getParents($cate, $v['pid']), $arr);//组合数组
         }
      }
      return $arr;
   }  
   /*传递一个父级分类ID求出所有子分类*/
   static public function getChilds($cate, $pid = 0)
   {
      $arr = array();
      foreach($cate as $v)
      {
         if($v['pid'] == $pid)
         {
            $arr[] = $v['id'];//返回ID如要返回所有只需$V
            $arr = array_merge($arr, self::getChilds($cate, $v['id']));
         }
      }
      return $arr;
   }  
}
?>

  

posted @ 2015-03-19 16:49  LoveProgram  阅读(219)  评论(0编辑  收藏  举报