Pick all dates of a day of the week

Asked

Viewed 700 times

2

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

Ex. 5/06/2017 = Monday.

The code is working perfectly. But it 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 spend a array in place of $dia_semana

1 answer

2


Try it this way:

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
    )

)

P.S.: I made the change in the function only so that the table works with an array, so I suggest you do the proper processing and etc. You can also adapt to the receiving function an item or an array.

  • perfect friend, thanks for the answer. I will adapt with what precise, bad initially was this the problem.

  • For nothing, needing we are here! hehe

  • Raapaz, now a question, if not to pass an array returns an error. How I treat this to bring the result, regardless of whether it is array or string?

  • In PHP there is the "is_array" function you use it to check if the received value is an array, then you just do the remaining processing.

  • Heheheeh thanks again !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.