Array grouping hierarchically PHP / MySQL

4

I have the following structure in a table in the database. My intention is that when I make a select * from on it I can interact with the values so that I have an array in the hierarchical style. That is, whenever there is an idFather, this value must be the child of a normal id that contains that value.

Example:

[
  Id: 01,
  idFather: null,
  Name: "Galpão",
  Sub: [
     Id: 02,
     idFather: 01,
     Name: "Bloco A,
  ]
]

UPDATED

This is basically my current code that assembles a single object without subcategories.

What could I do in it to achieve my goal?

public function getCategorias(CategoriaCollection $objCategorias){

$data = [];

foreach($objCategorias as $objCategoria){

    $data[] = (object) [
        'id' => $objCategoria->getId(),
        'pai' => $objCategoria->getPai(),
        'nome' => $objCategoria->getNome(),
    ];

}

parent::responderAjax(new AjaxResponse("", $data));

}

Any suggestions?

    
asked by anonymous 06.06.2018 / 12:20

1 answer

1

Look, as suggested in this topic link , here is an example recursive algorithm:

function build_tree($nodes, $parent=0)
{
  $branch = [];

  foreach($nodes as $node) {
    if ($node['parent'] == $parent) {
      $childrens = build_tree($nodes, $node['id']);

      if (!empty($childrens)) {
        $node['children'] = $childrens;
      }

      $branch[] = $node;
    }    
  }

  return $branch;

}


$categories = [
    ['id' => 1, 'parent'=> 0, 'name' => 'Galpão'],
    ['id' => 2, 'parent'=> 1, 'name' => 'Bloco A'],
    ['id' => 3, 'parent'=> 1, 'name' => 'Bloca B'],
    ['id' => 5, 'parent'=> 2, 'name' => 'Sala 1'],
    ['id' => 6, 'parent'=> 2, 'name' => 'Sala 2'],
    ['id' => 8, 'parent'=> 3, 'name' => 'Sala 1'],
    ['id' => 9, 'parent'=> 3, 'name' => 'Sala 2'],
];


var_dump(build_tree($categories));

I did some testing and it worked fine.

    
01.08.2018 / 20:47