How to group results of a query?

1

I have the following query that brings the name of the recipe and the ingredients:

$query = ("
SELECT r.receita, i.ingrediente
FROM ptp_receitas r, ptp_receitas_ingredientes ri, ptp_ingredientes i
WHERE r.id = ri.idreceita
AND ri.idingrediente = i.id
AND r.id = ".$rid);
$db -> setQuery($query);
$results = $db -> loadObjectList();
foreach($results as $row){
    echo '<h1>'.$row->receita.'</h1>';
    echo '<h2>Lista de Ingredientes:</h2>';
    echo $row->ingrediente;

}

The problem is that this way he repeats the recipe name on all ingredient lines, for example:

Receita de Arroz
arroz
Receita de Arroz
sal

I wanted you to come:

Receita de arroz
arroz
sal
    
asked by anonymous 12.04.2018 / 22:31

1 answer

3

Do the following logic with an auxiliary variable that will solve your problem:

$query = ("
SELECT r.receita, i.ingrediente
FROM ptp_receitas r, ptp_receitas_ingredientes ri, ptp_ingredientes i
WHERE r.id = ri.idreceita
AND ri.idingrediente = i.id
AND r.id = ".$rid);
$db -> setQuery($query);
$results = $db -> loadObjectList();

$count = 0;
foreach($results as $row){
    if($count != $row->idreceita){
        echo '<h1>'.$row->receita.'</h1>';
        echo '<h2>Lista de Ingredientes:</h2>';
        $count=$row->idreceita;
    }
    echo $row->ingrediente;

}

This will print <h1> Nome da Receita</h1> and the <h2> line only 1x per recipe.

    
12.04.2018 / 22:49