Multidimensional array from mysql query

2

Good afternoon,

I have a system, with the following tables:

pagina: id,nome ,icone, idGrupo.
paginaGrupo: id,nome,icone, idGrupoUser.

I am putting a dynamic menu on top of these tables. I get the ids of the groups that the user is part of, and I play in the query to get the Groups of pages and the pages that he will have access.

The query looks like this:

SELECT gp.id as idG,gp.nome grupo,gp.uri uriG,gp.ordemMenu,gp.icone as iconeG,'
. 'p.id,p.name as pagina,p.uri uriP ,p.icon as iconeP from tblPaginas as p '
. 'inner join tblGrupoPaginas as gp '
. 'on (p.idGrupo = gp.id) '
. 'where gp.idGrupoAcesso IN('.implode(",",$this->getUserGrupoId() ).') '
. 'order by gp.ordemMenu ASC

So, I get this return:

Array ( 
    [0] => Array ( 
        [idG] => 1 
        [grupo] => Monitoria de vendas
        [uriG] => monitoria-de-vendas 
        [ordemMenu] => 1 
        [iconeG] =>  
        [id] => 14 
        [pagina] => agenda 
        [uriP] => agenda 
        [iconeP] =>
    ) 
    [1] => Array ( 
        [idG] => 1 
        [grupo] => Monitoria de vendas 
        [uriG] => monitoria-de-vendas 
        [ordemMenu] => 1 
        [iconeG] =>  
        [id] => 15 
        [pagina] => paginas 
        [uriP] => paginas 
        [iconeP] =>  
    )
    [....]  
    [45] => Array ( 
        [idG] => 7 
        [grupo] => Ferramentas 
        [uriG] => ferramentas 
        [ordemMenu] => 8 
        [iconeG] =>  
        [id] => 10 
        [pagina] => equipamentos 
        [uriP] => equipamentos 
        [iconeP] =>  
    )

In the array, it has the 'idG' field. I would like the return to be from a multidimensional array above the value of the 'idG' field.

If there is no way to return the query, how could I do this to create this array through PHP?

Thank you in advance.

    
asked by anonymous 19.09.2016 / 17:38

1 answer

2

In comments, it is done in PDO , in itself has a way to group by a certain field , where it should be the first SQL item, this field being the array key :

Iwanttogroupbygrupoid,sousePDO::FETCH_GROUP|PDO::FETCH_ASSOCwithinfetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC):

<?php$pdo=newPDO('mysql:host=localhost;dbname=dbase','root','senha');$query=$pdo->query('SELECTgrupoid,id,descricaoFROMitemORDERBYgrupoid');$query->execute();$result=$query->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);var_dump($result);

Output:

array(2){[1]=>array(2){[0]=>array(2){["id"]=>
      string(1) "1"
      ["descricao"]=>
      string(7) "Grupo 1"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(1) "2"
      ["descricao"]=>
      string(7) "Grupo 1"
    }
  }
  [2]=>
  array(1) {
    [0]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["descricao"]=>
      string(7) "Grupo 2"
    }
  }
}

The key is grupoid .

Link:

19.09.2016 / 20:46