Ver Mensaje Individual
  #6 (permalink)  
Antiguo 18/09/2008, 01:45
Avatar de Lord of freaks
Lord of freaks
 
Fecha de Ingreso: octubre-2004
Ubicación: Madrid
Mensajes: 334
Antigüedad: 19 años, 6 meses
Puntos: 2
Respuesta: Consulta + Array + Arbol de Categorias

Hola

El resultado no es exactamente como tu pedías pero creo que mejora y que el array que devuelve es bastante más sencillo de parsear para hacer un menú o un breadcrum que creo que es lo que buscar:

Código:
<?php
$categorias = array (1 => array (4 => 'Aventura' ), 

0 => array (3 => 'Celulares', 1 => 'LIbros', 2 => 'Zapatos' ), 

4 => array (5 => 'Infantil' ) 
);

function &array_find_element_by_key($key, &$tree) {
  if (array_key_exists($key, $tree)) {
    $ret =& $tree[$key];
    return $ret;
  }
  foreach ($tree as $k => $v) {
    if (is_array($v)) {
      $ret =& array_find_element_by_key($key, $tree[$k]);
      if ($ret) {
        return $ret;
      }
    }
  }
  return FALSE;
}

function set_element_by_key($key,&$tree,$val){
	if (array_key_exists($key, $tree)) {
		$tree[$key]['childrens'] = $val;
		ksort($tree[$key]['childrens']);
	    return true;
	  }
	 foreach ($tree as $k => $v) {
	    if (is_array($v)) {
	      $ret = set_element_by_key($key, $tree[$k],$val);
	      if ($ret) {
	        return true;
      	}
    }
  }
  return FALSE;
}

function formatValue($val){
	$return = array();
	foreach ($val as $k => $v) $return[$k] = array('title' => $v,'childrens' => array());
	return $return;
}

$tree = array();
function getTree($categorias,$parent = 0){
	global $tree;
	if($parent === 0) {
		$tree = array('title' => 'home','childrens' => array());
		foreach($categorias[0] as $k => $v){
			$tree['childrens'][$k] = array('title' => $v,'childrens' => array());
			ksort($tree['childrens']);
		}
		unset($categorias[0]);	
	}
	
	foreach ($categorias as $key => $childrens){
			
			if ($newval = array_find_element_by_key($key, $tree)){
				set_element_by_key($key,$tree,formatValue($childrens));
			}
			$parent = $key;
		}
	
	return $tree;
}
echo "<pre>";
print_r(getTree($categorias));
echo "</pre>";
?>
__________________
Una vez un elemental de rayos mató una tribu entera de tritones.

¡¡ El sólo quería darse un baño !!

http://www.frikilandia.com

Neither Fu Nor Fa

Última edición por Lord of freaks; 18/09/2008 a las 03:37 Razón: Ahora devuelve los arrays "children" ordenados por key para hacerlo más jerárquico