Extrayendo datos mensuales de la matriz php

I have an array containing dates i want to make subsets of this array month wise? dates in array are in format i.e. $dates = array('2010-11-01',.....);

preguntado el 09 de enero de 11 a las 09:01

What's your problem? What have you tried? -

How are your dates formatted? -

2010-11-01 is ambiguous. Is that YYYY-MM-DD or YYYY-DD-MM? -

What is the expected result ? -

3 Respuestas

There is no need to use the date class. Instead, we can just use substr() to get the YYYY-MM and index by that.

$dates = array('2010-11-11', '2010-01-14', '2010-01-17', '2011-01-03');
$months = array();
foreach($dates as $date) {
  $month = substr($date, 0, 6);
  $months[$month][] = $date;
}
print_r($months);

Salida:

Array
(
    [2010-1] => Array
        (
            [0] => 2010-11-11
        )

    [2010-0] => Array
        (
            [0] => 2010-01-14
            [1] => 2010-01-17
        )

    [2011-0] => Array
        (
            [0] => 2011-01-03
        )

)

Respondido el 09 de enero de 11 a las 13:01

Note: It will not only support your date format but also many other date formats. You can also use months in numeric or alphabetical representation.

You can loop it something like this:

$arr = array( '2009-1-1', '2009-2-1','2009-3-1','2009-3-1' );

$output = array();

foreach( $arr as $date ){
   $output[date('m', strtotime($date))][] = $date; 
}

print_r($output);

Test It Here



You can use month name also:

$output[date('M', strtotime($date))][] = $date; 

Test It Here



For year wise months you can do it something like this:

$output[date('y', strtotime($date))][date('m', strtotime($date))][] = $date;

Test It Here

Respondido el 09 de enero de 11 a las 20:01

Since when was January 2010 == January 2011? :) - Moinudin

@marcog: It was an example. May be someone want to get person's birthdays months wise then there is no need for year. Anyway we can also do it year wise. Answer is edited. - Naveed

I haven't tested this at all, but assuming the array $dates is made up of timestamps, the following should work

$months = array();
foreach($dates as $date) {
$months[date('F', $date)][] = $date;
}

Respondido el 09 de enero de 11 a las 12:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.