Skip to content
Todo se AprendeAyuda y trucos para programación
  • Home
  • Categorías
    • Debian
    • JS
    • PHP
    • WordPress
    • MySql
    • Cordova

Build Tree Array PHP

30/06/2020 0 comments Article PHP

Como crear un array árbol, con la siguiente función se crea solo, el array plano tiene que tener lo siguiente.

Array => (‘id_hijo’,’nombre_hijo’,’id_padre’) tiene que ser indexado por numero 0,1,2 etc… (FETCH::NUM)

Ej.:
Array
(
[0] => id_hijo
[1] => nombre
[2] => id_padre
[3] => etc…
)

La función:

function buildTree(array &$elements, $parentId = 0,$level = 0) {
      $branch = array();
      foreach ($elements as &$element) {
        if ($element[2] == $parentId) {
          $children = $this->buildTree($elements, $element[0],$level+1);
          if ($children) {
            $element['children'] = $children;
          }
          $element['level'] = $level;
          $branch[$element[0]] = $element;
          unset($element);
        }
      }
      return $branch;
    }

$tree = buildTree($array);

Luego podemos hacer lo que queramos con el árbol, por ejemplo crear un select option.

function optionSelect($value,$seleccionado,$texto){
      $selected = $value == $seleccionado ? "selected" :  "";
      $option = "<option title='$texto' value='$value' $selected>$texto</option>";
      return $option;
    } 
function walkTreeSelectOption($elements,$seleccionado = ''){
      $return = '';
      foreach($elements as &$value){

        if($value['level'] == 0)
          $return .= '<optgroup label="'.$value[1].'">';

        $texto = str_repeat("- ", $value['level']).$value[1];

        $return .= $this->optionSelect($value[0],$seleccionado,$texto);

        if (isset($value['children'])):
          $return .= $this->walkTreeSelectOption($value['children'],$seleccionado);
        endif;

        if($value['level'] == 0)
          $return .= '</optgroup>';
      }
      return $return;
    }

$options = walkTreeSelectOption($tree,'id_hijo') // podemos pasarle el id_hijo para que se seleccione en el select

Aquí si queréis pasar el build tree de nuevo a array pero ordenado link

0 0 vote
Article Rating
Tags: arbol, build, buildTree, option, php, select, tree, walkTree
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments

Entradas recientes

  • Tabla SQL población España
  • Validar DNI (NIF), CIF, NIE
  • Table tr collapsible Jquery
  • Build Tree to flat array PHP
  • Build Tree Array PHP

Categorías

  • Cordova
  • Debian
  • JS
  • MySql
  • PHP
  • Sin categoría
  • WordPress

Archivos

Copyright Todo se Aprende 2021 | Theme by ThemeinProgress | Proudly powered by WordPress

wpDiscuz
Utilizamos cookies para asegurar que damos la mejor experiencia al usuario en nuestro sitio web. Si continúa utilizando este sitio asumiremos que está de acuerdo.Estoy de acuerdoLeer más