How can I format this array the way I want it?

4

I am creating a Seeder for Laravel insert values into a N para N table.

I'm setting up array in one way, but I need it to become "in another" in the end. This is because I want to avoid constant code repetition (repeatedly typing the same items as array .

The array I have is the following:

  $niveis[3] = [
        $can('VendaController@getIndex'),
        $can('VendaController@anyEditar'),
        $can('VendaController@anyCriar'),
 ];

 $niveis[14] = [
        $can('ProdutoController@getIndex'),
        $can('UsuarioController@anyEditar'),
        $can('UsuarioController@anyCriar'),
 ];

This generates a array like this:

 [ 
   3 => [1, 55, 87],
   14 => [45, 78, 101]
]

But I need that from this array , I can mount it as follows:

[
      [ 'nivel_id' => 3, 'permissao_id' => 1],
      [ 'nivel_id' => 3, 'permissao_id' => 55],
      [ 'nivel_id' => 3, 'permissao_id' => 87],
      // E assim por diante

   ]

That is, I need to convert key to nivel_id to its value, and repeat as long as it has some value within array for it.

How to do this in PHP, in a less complicated way?

    
asked by anonymous 26.04.2016 / 16:01

2 answers

3

As I understand it, this is it:

 $array = [ 
   3 => [1, 55, 87],
   14 => [45, 78, 101]
];


 $novoArray = [];

 foreach($array as $key => $subArray) {
    foreach($subArray as $value) {
        $novoArray[] = [
           'nivel_id' => $key, 'permissao_id' => $value
         ];
    }
 }


 print_r($novoArray);
    
26.04.2016 / 16:26
0

There's no getting away from the loop.

Basically you will go through the first index, hitting the level. Each level should get the permissions and thus map a new array with the new format.

Here's an example:

link

    
26.04.2016 / 16:58