How to bring SQL result grouped by year and within months

0

I have a table like this:

data               |id
2017-02-01 00:00:00|1
2017-02-01 00:00:00|5
2017-04-01 00:00:00|2
2018-02-01 00:00:00|3
2018-04-01 00:00:00|4

Then I make a query with PHP in Mysql that brings me

SELECT id, data
FROM orders
GROUP BY data

and brings in php

foreach($results as $row){
echo date('m',$row->data).'<br/>';
}

The above result is:

02
04
02
04

But I wanted him to bring it together by year:

2017
02
04

2018
02
04
    
asked by anonymous 05.04.2018 / 20:55

2 answers

1

Well, not knowing what is coming back is very difficult to answer. You can try with this code. It creates an array to group its results into a multidimensional array.

foreach($results as $row){
    $mes = date('m',$row->data);
    $ano =  date('y',$row->data);
    $dia = date('d', $row->data);
    $intervals[$ano][$mes] = $dia;

}

foreach($intervals as $ano => $meses){
    echo $ano . "</br></br>";
    foreach($meses as $mes => $dia){
        echo $mes . "</br>";
    }
}
    
05.04.2018 / 21:08
0

First problem in your code is that if the date is the same and the time different, they will not be grouped, so ideally you group by year and month of date, select would look like this:

SELECT id, data
FROM orders
GROUP BY YEAR(data), MONTH(data);

On-screen printing would look like this:

$anoAnterior = '';
foreach($results as $row){
    $anoAtual = date('Y', $row->data)
    if (($anoAnterior != '') && ($anoAnterior != $anoAtual))
        echo "<br />";
    if ($anoAnterior != $anoAtual)
        echo $anoAtual.'<br />';
    echo date('m', $row->data).'<br/>';
}
    
05.04.2018 / 21:35