Group items by a field into different arrays

Asked

Viewed 781 times

2

 $resultado = $modelSga->getConsultaSga($ano, $mes, $unidade);

                foreach ($resultado as $res) {

                        $idServico = $res->id_serv;

                        $servico = array();
                        if($idServico != $idServicoAnterior) {
                            array_push($servico, $res->nm_serv);
                        echo($servico[0]);
                        }
                        echo "<br/>";

                }

What I’m trying to do is for every ID_SERV different he’ll take the nm_serv and store in a array grouping. This will be useful as I will create a table for each different information. ex:

SECTOR
car
car
car
car

SECTOR
motorcycle
motorcycle
motorcycle
motorcycle

SECTOR
....
....
....

tabelas que devem sair

  • 1

    I don’t understand. Can you describe it a little better? Especially in the title that doesn’t say what your problem is.

  • 1

    Can you clarify better what you want? do not understand bulbs...

  • So, I will assemble a table of 5 columns only that the information will be divided, IE, each id_serv (which is also nm_serv) will turn a table, type image I posted.

  • id_serv is what I believe I will use to divide the tables.

2 answers

8


It’s probably easier to make the output stay in a sub-array:

$saida = array();
foreach ($resultado as $res) {
   //se o indice id_serv ainda nao estiver na $saida, adicionamos uma array vazia:
   if( !isset( $saida[$res->id_serv] ) ) {
      $saida[$res->id_serv] = array();
   }
   //acrescentamos o item na subarray desejada:
   array_push( $saida[$res->id_serv], $res->nm_serv );
}

If you want to put multiple fields in the output array, just do it this way:

array_push( $saida[$res->id_serv], array(
   'Matricula'    => $res->matricula,
   'Nome'         => $res->nome,
   'Atendimentos' => $res->atendimentos
) );

See working on IDEONE

To use as if they were separate arrays and mount a table, just do this later:

foreach( $saida as $grupo => $itens ) {
    echo "<h1>$grupo</h1>";
    foreach( $itens as $item ) {
       echo 'Matricula: '.$item['Matricula'];
       echo 'Nome: '     .$item['Nome'];
       ... etc ...
    }
}
  • 1

    worked perfectly, and the way you went through I’ll be able to even more easily do what I want, unfortunately I still complicate with arrays. Thanks.

2

The main problem with your code is that you are clearing the array each loop.

foreach ($resultado as $res) {
   ...
   $servico = array();

For this type of logic you must declare the array outside the loop and only increase it.

$servico = array();
foreach ($resultado as $res) {
   {...}
   array_push($servico, $res->nm_serv);
   {...}
}

(If I understand correctly the problem...)

Browser other questions tagged

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