Grouping arrays hierarchically PHP / Mysql

Asked

Viewed 164 times

4

I have the following structure in a table in the database. My intention is that when I do a select * from in it I can interact up the values so that I have an array in the hierarchical style. That is, whenever there is an idFather, this value must be a child of a normal id that contains this 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 mounts a single object without subcategories.

What I could 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?inserir a descrição da imagem aqui

  • 1

    suggestion would be to use a recursive function or be called itself, so you can mount the pertendido array

  • I get it, but I’m having trouble imagining the logic for this recurse function, could you give me a hint? I updated the question with my current code. @13dev

1 answer

1


Look, as suggested in this topic https://stackoverflow.com/a/8587437/476, follows an example of 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 tests and it worked well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.