k_turek
k_turek

Reputation: 341

Group by date on timeline

I have a table from which I get the date and quantity. I display it as timelines.

   $show = $this->__db->execute("SELECT date, quantity from table");

            foreach($show as $show_)
            { 
             echo "{$show_['date']} - {$show_['quantity']}";
            }

I receive:

| 2020-11-12 - 2541
| 2020-11-12 - 2541
| 2020-10-21 - 2541
| 2019-07-02 - 4112
| 2018-03-30 - 1234

but I wish I had something like this

    | 2020-11-12 - 2541
    | 2020-11-12 - 2541
    | 2020-10-21 - 2541
  2019
    | 2019-07-02 - 4112
  2018
    | 2018-03-30 - 1234

etc... the same year I downloaded with

SELECT YEAR(data) from table

but I don't know how to invoke the year when it changes...

Upvotes: 0

Views: 139

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13635

We can store the year from the last record in a variable to see when it changes:

// Since we don't want to print the current year, let's add it as default.
// If you want to print the current year as well, then just set this variable as null.
$theYear = date('Y');

foreach($show as $show_)
{ 
    // Get the year from this record
    $recordYear = date('Y', strtotime($show_['date']));

    if ($theYear !== $recordYear) {
        // They are not the same which means the year have changed 
        // and we want to print it out
        echo $recordYear;

        // Now store the record year as the year so we don't echo it again
        $theYear = $recordYear;
    }

    echo "{$show_['date']} - {$show_['quantity']}";
}

Upvotes: 1

Markus Zeller
Markus Zeller

Reputation: 9135

Just record if the year has changed. If yes, display it.

$data = [
    ['date' => '2020-11-12', 'quantity' => 2541],
    ['date' => '2020-11-12', 'quantity' => 2541],
    ['date' => '2020-10-21', 'quantity' => 2541],
    ['date' => '2019-07-02', 'quantity' => 4112],
    ['date' => '2018-03-30', 'quantity' => 1234]
];

$lastYear = '';
foreach($data as $row) {
    list($year,,) = explode('-', $row['date']);
    if($year !== $lastYear) {
        echo $year, PHP_EOL;
        $lastYear = $year;
    }
    echo "  | {$row['date']} - {$row['quantity']}", PHP_EOL;
}

Will output

2020
  | 2020-11-12 - 2541
  | 2020-11-12 - 2541
  | 2020-10-21 - 2541
2019
  | 2019-07-02 - 4112
2018
  | 2018-03-30 - 1234

Upvotes: 2

Related Questions