Ver Mensaje Individual
  #6 (permalink)  
Antiguo 04/09/2009, 01:31
samu22
 
Fecha de Ingreso: abril-2008
Mensajes: 453
Antigüedad: 16 años, 1 mes
Puntos: 16
Respuesta: Problema listando categorias

bueno gente, pude acomodar este listado complicado, paso a detallar por si alguien se ve envuelto en una situacion tan engorrosa como la que tuve:

estructura de la base
-Tabla categorias
Código:
id
categoria_id
nombre
- Tabla categorias_post
Código:
id
categoria_id
post_id
-Tabla post
Código:
id
tipo_id
titulo
contenido
estado
fecha_ini
fecha_mod
keywords
esta ultima no hace haria falta mostrar pero es para mostrar todas las tablas que se nombran en el codigo del listado

Obtencion de los datos antes de recorrer e imprimir
modelo->multimedia
Código php:
Ver original
  1. function getPostByCategoriaId($catId){
  2.         global $DbConn;
  3.         $sql = 'SELECT post_id, titulo FROM categorias_post AS tcat
  4.                 LEFT JOIN categorias AS tc ON tcat.categoria_id = tc.id
  5.                 LEFT JOIN post AS tp ON tcat.post_id = tp.id
  6.                 WHERE tcat.categoria_id ='.$catId.' AND tipo_id ='.$this->get('tipo_id',$this->model);
  7.         // $this->get(tipo,$this->model) es una funcion que devuelve el tipo de post
  8.        // del modelo actual, podria ser noticias, multimedia, articulos, etc
  9.         $res = $DbConn->query($sql);
  10.         $i = 0;
  11.         while($row = $DbConn->fetchAssoc($res)){
  12.             $data[$i]=$row;
  13.             $i++;
  14.         }
  15.         return $data;
  16.       }
  17.      
  18.     function getNumPostByCategoria($idCategoria){
  19.         global $DbConn;
  20.         $sql = 'SELECT COUNT(p.id) AS NUM FROM post p
  21.                 LEFT JOIN categorias_post cp ON p.id = cp.post_id
  22.                 WHERE cp.categoria_id = '.$idCategoria.' AND tipo_id = '.$this->get('tipo_id',$this->model);
  23.         $resul = $DbConn->fetchArray($DbConn->query($sql));
  24.         return $resul['NUM'];
  25.     }  
  26.    
  27.     function getNumHijosByCategoria($idCategoria){
  28.         global $DbConn;
  29.         $sql = 'SELECT COUNT(id) AS NUM FROM categorias WHERE categoria_id ='.$idCategoria;
  30.         $resul = $DbConn->fetchArray($DbConn->query($sql));
  31.         return $resul['NUM'];
  32.     }
  33.    
  34.     function crearArboles($parent='0',$ini){
  35.         global $DbConn;
  36.         //buscamos las categorias con el parent
  37.         $sql = 'SELECT * FROM categorias WHERE categoria_id ='.$parent;
  38.         $res = $DbConn->query($sql);
  39.         $numR = $DbConn->numRows($res);
  40.         while($arr = $DbConn->fetchArray($res)){
  41.             //comenzamos a recorrer una por una, primero vamos a comprobar si tiene post
  42.                 $arrRet[$ini]['id'] = $arr['id'];
  43.                 $arrRet[$ini]['categoria'] = $arr['Nombre'];
  44.                 if($this->getNumPostByCategoria($arr['id'])>0){
  45.                    $arrRet[$ini]['post'] = $this->getPostByCategoriaId($arr['id']);
  46.                 }
  47.                
  48.                 if($this->getNumHijosByCategoria($arr['id'])>0){
  49.                    $arrRet[$ini]['hijo'] = $this->crearArboles($arr['id'],$ini);
  50.                 }
  51.                 $ini++;            
  52.            
  53.         }                  
  54.                
  55.        
  56.        
  57.         return $arrRet;
  58.        
  59.     }

esto nos devuelve un array con una estructura similar a
Código:
{
   [0] =>Array
                  {
                       [id] => 1
                       [categoria] => Primera Categoria
                       // en el caso que exista un post asignado a esa categoria
                       [post] => Array
                                       {
                                          [0] => Array
                                                     {
                                                        [id] => 1
                                                        [titulo] => pos con categorias
                                                      }
                                       }
                       // si tuviera algun hijo (seria un padre excelente)
                       [hijo] => Array
                                     { 
                                          [0] => Array
                                                (
                                                     [id] => 2
                                                     [categoria] => Educación ambiental
                                                     //estas a su vez si tuvieran post quedaria como la de arriba y lo mismo si tuviera hijos
                                                 )
                                      }

                    }
}

ya tenemos nuestro array con los datos de la categorias

La vista se encarga de reccorer este array y hacer las comparaciones para que, si tiene algun post, o si no tiene pero alguno de sus hijos o nietos o bisnietos tiene liste la categoria y el desgrosado de la misma

vista -> index.php
Código php:
Ver original
  1. function recorrer($objet){
  2.        
  3.         foreach($objet as $num => $padre){
  4.             $mTitulo = false;
  5.             // si tiene post
  6.             if(!empty($padre['post'])){
  7.                 $mTitulo = true;
  8.             }
  9.             // si tiene hijos
  10.             if(!empty($padre['hijo'])){
  11.                 //buscamos que tengan post, en el caso de tener hijos volveria a hacer la recursiva
  12.                 //y al cumplir la condicion retornaria el dato
  13.                 foreach($padre['hijo'] as $num => $hijo){
  14.                     // si tiene un post debe mostrar el titulo del padre
  15.                     if(!empty($hijo['post'])){
  16.                         $mTitulo = true;
  17.                     }else{
  18.                         if(!empty($hijo['hijo'])){
  19.                             recorrer($hijo['hijo']);
  20.                         }
  21.                     }
  22.                 }
  23.             }
  24.             if($mTitulo){
  25.                 $html .= '<ul>';
  26.                     $html .= '<h1><a href="javascript:void(0)">'.$padre['categoria'].'</a></h1>';
  27.                     $html .= '<ul>';
  28.                     //recorremos los datos del post
  29.                         foreach($padre['post'] as $num => $post){
  30.                             $html .= '<li><a href="'.ROOT_PATH.'/post/ver/id/'.$post['post_id'].'"> '.$post['titulo'].'</a></li>';
  31.                         }
  32.                     $html .= '</ul>';
  33.                     // verificamos si tiene hijos
  34.                         if(!empty($padre['hijo'])){
  35.                             $html .= '<ul>';
  36.                             $html .= recorrer($padre['hijo']);
  37.                             $html .= '</ul>';
  38.                         }
  39.                     $html .= '</ul>';
  40.             }else{
  41.                 $html .= '<ul></ul>';
  42.             }
  43.            
  44.         }
  45.         return $html;
  46.     }
  47.  
  48.  
  49.         // $lista es el array que nos proporciona el modelo
  50.        echo recorrer($lista);