Group items by one field in different arrays

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 am trying to do is for every ID_SERV different it will get the nm_serv and store it in a grouping array . This will be useful since I will create a table for each different information. ex:

SECTOR
car
car
car
car

SECTOR
motorcycle motorcycle motorcycle motorcycle

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

    
asked by anonymous 31.10.2014 / 16:18

2 answers

5

It's probably simpler to make the output 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 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 at IDEONE

To use as 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 ...
    }
}
    
31.10.2014 / 16:34
2

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

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

For this type of logic you should declare the array out of loop and just increment it.

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

(If I understood correctly the problem ...)

    
31.10.2014 / 16:41