B
B
BarneyGumble2018-09-05 18:07:13
Yii
BarneyGumble, 2018-09-05 18:07:13

How is it better to organize a tree-like output of dates (year, month) of articles along with their number in PHP (Yii2)?

There is a base with articles. Each article has a creation date in YYYY-MM-DD format.
From the database
It is necessary to display links in a tree to filter articles by dates so that it looks something like this:
2018
August (9)
October (3)
December (1)
2017
January (12)
March (3)
July (5)
2016
June (4)
October ( 7)
December (2)
What is the best way to implement this?
When there was a task to display just months within one year, I solved it like this:

<?php 
       foreach($dates as $date) {
             $monthsArray[] = Yii::$app->formatter->asDate($date->date, 'M');   
        }    
       $monthsUniqueArray = array_count_values ($monthsArray);
 ?>

<?php foreach( $monthsUniqueArray as $key => $value):?>
        <p><a href="<?= Url::toRoute(['site/index', 'date'=>$key]);?>"><?=$key?></a> <small class="text-muted"><?=$value?></small></p>
<?php endforeach; ?>

But, obviously, this is a stiff and not universal solution. When the years appeared, I stuck something (
From the database it is possible to get both an array of dates: And an array of articles with dates: Which one is more correct to enumerate?
$dates = Articles::find()->select('date')->all();
$articles = Articles::find()->all();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-09-05
@webinar

Need a query in the database grouped by month, if the date in the database as a number - I sympathize.
Smoking page: https://yandex.ru/search/?text=mysql%20group%20by%...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question