Two-dimensional array in variable

1

I have been given a array two-dimensional% with the holidays of SPAIN and I have a function that calculates the working days without counting the end of weeks.

I do not want you to tell me about the holidays that are in that array , I've put two test days only.

My problem is that the function does not work very well when I put the days of array . I tried to show them and if it works but I do not know how I can go through the array and put the data in a variable.

Here is the code:

function diashabiles($fechainicio, $fechafin){
$inicio = new DateTime($fechainicio);
$final = new DateTime($fechafin);
// Meter fecha final en la operación.
$final->modify('+1 day');

$intervalo = $final->diff($inicio);

//Días totales
$dias = $intervalo->days;

// Creamos un perido para que imprima los días (P1D es igual a 1 dia)
$periodo = new DatePeriod($inicio, new DateInterval('P1D'), $final);

//Array con días de fiesta
$holidays = array(
        array('2018-01-01'),
        array('2018-02-28'));


//echo " ".$holidays[1][0]." ";

//foreach($holidays as $di){
//  echo $di[0][0];
//}

foreach($periodo as $d) {
    $pos = $d->format('D');

    if ($pos == 'Sat' || $pos == 'Sun') {
        $dias--;
    }

    elseif (in_array($d->format('Y-m-d'), $holidays)) {
        $dias--;
    }
}

return $dias;
}
$d = diashabiles('2018-01-01 00:00:00','2018-01-01 00:00:00');
echo $d;
    
asked by Alvaro Roman 21.02.2018 в 13:20
source

1 answer

0

A simple solution is to transform the $holidays array to a flat array.

For this you can use call_user_func_array e in conjunction with array_merge

Example:

<?php
function diashabiles($fechainicio, $fechafin) {
    $inicio = new DateTime($fechainicio);
    $final = new DateTime($fechafin);
    // Meter fecha final en la operación.
    $final-> modify('+1 day');

    $intervalo = $final->diff($inicio);

    //Días totales
    $dias = $intervalo->days;

    // Creamos un perido para que imprima los días (P1D es igual a 1 dia)
    $periodo = new DatePeriod($inicio, new DateInterval('P1D'), $final);

    //Array con días de fiesta
    $holidays = array(
        array('2018-01-01'),
        array('2018-02-28'),
    );
    // AQUI Convertimos el arreglo de bidimensional a plano
    $holidays = call_user_func_array('array_merge', $holidays);

    foreach($periodo as $d) {
        $pos = $d->format('D');

        if ($pos == 'Sat' || $pos == 'Sun') {
            $dias--;
        } else if (in_array($d->format('Y-m-d'), $holidays)) {
            $dias--;
        }
    }

    return $dias;
}

$d = diashabiles('2018-01-01 00:00:00', '2018-01-01 00:00:00');
echo $d;
?>

Demo

    
answered by 21.02.2018 / 13:38
source