Get all the dates of a day of the week

2

I have a code that takes all dates on a certain day of the week.

Ex. 5/06/2017 = Monday.

The code is working perfectly. More is limited only 1 day of the week, I would like to "spend" more days an array.

function dias($dia_semana, $mes, $ano)
{
    $date = new DateTime();
    $dias = cal_days_in_month(CAL_GREGORIAN, $mes, $ano);

    for ($dia = 0; $dia <= $dias; $dia++)
    {
        $date->setDate( $ano, $mes, $dia );

        if ($date->format( "w" ) == $dia_semana)
        {
            $datas[] = $dia."/".$mes."/".$ano;
        }
    }

    return $datas;
}
print_r(dias("1","06","2017");
// "1"    = 0 = domingo até o 6 = Sábado 
// "06"   = mês
// "2017" = Ano

I wanted to pass array instead of $dia_semana

    
asked by anonymous 22.06.2017 / 19:12

1 answer

2

Try this:

function dias($dias_semana, $mes, $ano)
{
    $date = new DateTime();
    $dias = cal_days_in_month(CAL_GREGORIAN, $mes, $ano);

    for ($dia = 0; $dia <= $dias; $dia++)
    {
        $date->setDate( $ano, $mes, $dia );
        foreach ( $dias_semana as $_dia ) {
            if ($date->format( "w" ) == $_dia)
            {
                $datas[$_dia][] = $dia."/".$mes."/".$ano;
            }    
        }

    }

    return $datas;
}
print_r(dias([1,2],"06","2017"));

// Resultado
Array
(
    [1] => Array
    (
        [0] => 5/06/2017
        [1] => 12/06/2017
        [2] => 19/06/2017
        [3] => 26/06/2017
    )

[2] => Array
    (
        [0] => 6/06/2017
        [1] => 13/06/2017
        [2] => 20/06/2017
        [3] => 27/06/2017
    )

)

Q: I made the change in function only for the table to work with an array, so I suggest you do the proper treatments and so on. You can also adapt the function to receive an item or array.

    
22.06.2017 / 19:35