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

Asked

Viewed 142 times

4

I’m creating a Seeder to the Laravel insert values into a table N para N.

I am riding the array in one way, but I need it to "become" in another. This is because I want to avoid repeating constant code (typing repeatedly the same items from array.

The array what I have is this:

  $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 thus:

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

But I need that from that array, I can ride him like this:

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

   ]

I mean, I need to transform the key in nivel_id with its value, and repeat as long as it has some value within the array concerning her.

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

  • 2

    Good question +1

  • @rray I have the small impression that it will take us to a array_map two-parameter

2 answers

3

From what I understand, 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);
  • 1

    Yeah, I’m thinking, thinking, thinking... and I still only found this way...

0

Browser other questions tagged

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