Result Grouped by Field and Listing N records

0

I have a table named area with the structure:

Id, Nome, Status

I have another table called news with the structure:

Id,Título,Descricao,Data,IdArea,Status

I would like to return all newsgroups grouped by area code, where the result would be grouped by Area ID, and would list N news.

Target format:

  [Id Área] 
    [idNoticia],[título],[descricao]
    [idNoticia],[título],[descricao]
    [idNoticia],[título],[descricao]
  [...]
  [...]   
    
asked by anonymous 26.09.2018 / 01:57

1 answer

1

Execute this query using the driver you want (PDO, mysqli_ * or mysql _ *):

SELECT idarea, id, titulo, noticia FROM noticia ORDER BY idarea;

Assuming the result of this query is an array and is in the variable $resultado :

$formatado = [];

foreach ($resultado as $linha) {
    if (!$formatado[$linha["idarea"]]) {
        $formatado[$linha["idarea"]] = [];
    }

    $formatado[$linha["idarea"]][] = $linha;
}

You can adapt the above code to use with numeric objects or arrays

    
26.09.2018 / 02:09