K
K
kschingiz2015-02-05 00:54:05
PHP
kschingiz, 2015-02-05 00:54:05

How to group values ​​in an array?

There is a calendar in the frontend that displays the number of events for a certain date. It can be like this: 5 events on February 15, 20 events on February 20.
The data is received in the following form:

[{
title: "Событие 1",
date_start:"2015-02-25";
date_end:"2015-02-25"
},
{
title: "Событие 2",
date_start:"2015-02-25";
date_end:"2015-02-28"
}]

Now the joke is such that you need to make an array of this type, the key of which is dates, and the values ​​are the number of events:
[{
2015-05-25: 2,
2015-05-26: 1,
2015-05-27: 1,
2015-05-28: 1,
}]

Here the problem is how to form such an array and how to take into account intersections, for example, Event 2 lasts from February 25 to February 28.
It is clear that you need to run through the array and increment the values ​​of the days, but how to form such an array above?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2015-02-05
@kschingiz

Probably, you need to consider the event for the entire duration of the event, that is, to consider it not only on the day it starts, but also on each day that it lasts.
Then you need to make a cycle for each event, and count this event for each day in the interval:

$dates = array();
foreach ($events as $event) {
    $dateStart = \DateTime::createFromFormat('Y-m-d', $event['date_start']);
    $dateEnd = \DateTime::createFromFormat('Y-m-d', $event['date_end']);
    while ($dateStart <= $dateEnd) {
        $date = $dateStart->format('Y-m-d');
        if (!isset($dates[$date])) $dates[$date] = 0;
        $dates[$date]++;
        $dateStart->modify('+1 day');
    }
}

A
Alexey Yakhnenko, 2015-02-05
@ayahnenko

judging by the second listing, only the start date of the event is taken into account.
those. the second event, although it lasts 3 days, will be shown only for the 1st.
in this case,

$calendar = array();
foreach ($events as $event) {
  $calendar[$event['date_start']] = isset($calendar[$event['date_start']]) ? 
    $calendar[$event['date_start']] + 1 : 
    1;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question