Mount Array with categories and subcategories that are in the same table

Asked

Viewed 85 times

-1

I am trying to assemble an array, but I am not getting, before the following table, I need to assemble the array as in the example below the photo.

6.x Standard design

tabela com as categorias e subcategorias

in the'categoria_id 'columns which is null' are main categories. And the 'categorias_id with id, are the subcategories, with the id of the main category, I need something with this example that I set below.

$categorias = Categorias::orderBy('id', 'ASC')->get();

$categoria = $categorias->where('categoria_id', '=', null)->toArray();

$subcategoria = $categorias->where('categoria_id', '!=', null)->toArray();

I even separated, but I can’t put them together, as shown in the example below.

Array
(
    [0] => Array
        (
            [id] => 1
            [categoria] => Lanches
            [categoria_id] => 
            [status] => 0
            [ordem] => 
            [subcats] => Array
               (
                     [3] => Array
                         (
                             [id] => 5
                             [categoria] => Lanches Tradicionais
                             [categoria_id] => 1
                             [status] => 0
                             [ordem] => 
                         )

                     [4] => Array
                         (
                             [id] => 6
                             [categoria] => Lanches Gourmet
                             [categoria_id] => 1
                             [status] => 0
                             [ordem] => 
                         )

                     [5] => Array
                         (
                             [id] => 7
                             [categoria] => Lanches Caseiros
                             [categoria_id] => 1
                             [status] => 0
                             [ordem] => 
                         )

                )
        )

    [1] => Array
        (
            [id] => 2
            [categoria] => Porções
            [categoria_id] => 
            [status] => 0
            [ordem] => 
        )

    [2] => Array
        (
            [id] => 4
            [categoria] => Sucos
            [categoria_id] => 
            [status] => 0
            [ordem] => 
        )

)

I’ve tried to ride in various ways, but no success, I don’t know what else to do.

  • you receive this information from the database in raw format?

  • yes, in Laravel.. return all categories..

  • updated the question, give a look

  • I made the answer and option 2 better solves your problem, take a look!

  • 1

    top bro! I had to leave, I arrived now I will test, but face I imagine it will solve, I already answer you

1 answer

2


  1. According to the first example:

First you need to filter the data you have categoria_id === null, example:

$arrayCategoria = array_filter($array, function ($item) {
  return empty($item['categoria_id']);
});

and then with the categories already separated you need to iterate on the items that are the categories and search in the array main Sub Categories with other array_filter:

for ($i = 0; $i < count($arrayCategoria); $i++) {
  $id = $arrayCategoria[$i]['id'];
  $arrayCategoria[$i]['cats'] = array_filter(
    $array,
    function ($item) use ($id) {
      return $item['categoria_id'] === $id;
    }
  );
}

Complete code:

<?php    
$array = [
  ['id' => 1, 'categoria' => 'Lanches', 
   'categoria_id' => null, 'status' => 0, 'ordem' => null],
  ['id' => 2, 'categoria' => 'Porções', 
   'categoria_id' => null, 'status' => 0, 'ordem' => null],
  ['id' => 4, 'categoria' => 'Sucos', 
   'categoria_id' => null, 'status' => 0, 'ordem' => null],
  ['id' => 5, 'categoria' => 'Lanches Tradicionais', 
   'categoria_id' => 1, 'status' => 0, 'ordem' => null],
  ['id' => 6, 'categoria' => 'Lanches Gourmet', 
   'categoria_id' => 1, 'status' => 0, 'ordem' => null],
  ['id' => 7, 'categoria' => 'Lanches Caseiros', 
   'categoria_id' => 1, 'status' => 0, 'ordem' => null],
];   

$arrayCategoria = array_filter($array, function ($item) {
  return empty($item['categoria_id']);
});    

for ($i = 0; $i < count($arrayCategoria); $i++) {
  $id = $arrayCategoria[$i]['id'];
  $arrayCategoria[$i]['cats'] = array_filter(
    $array,
    function ($item) use ($id) {
      return $item['categoria_id'] === $id;
    }
  );
}

echo '<pre>';
print_r($arrayCategoria);
echo '</pre>';

Online Link


  1. With Self Relationship

The other way would be for me the ideal where own Eloquent would solve with a Self Relationship Question I Asked Myself and the answer.

In his Model Categorias add a method:

//relacionamento (auto-relacionamento) item 4 
public function subCategorias()
{
    return $this->hasMany(Categorias::class, 'categoria_id', 'id');
}

and when using make the following code:

Categorias::with('subCategorias')->get();

Note: Use the second option is easier to maintain the evolution of the code and item 1. gets to do this code manually

  • 1

    You are very monster man! worked perfectly the 2nd option, but the 1st will also help, to do another thing, sensational! thank you bro!

Browser other questions tagged

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