Array search with conditions

0

I have a Array of records:

Array
(
    [0] => Array
        (
            [HANDLE] => 1
            [Z_GRUPO] => 
            [EMPRESA] => 1
            [FILIAL] => 1
            [DATAINICIO] => 2018-01-01 
            [CONSUMO] => 2
            [VEICULO] => 82
        )

    [1] => Array
        (
            [HANDLE] => 2
            [Z_GRUPO] => 
            [EMPRESA] => 1
            [FILIAL] => 1
            [DATAINICIO] => 2018-02-01
            [CONSUMO] => 2.5
            [VEICULO] => 82
        )

    [2] => Array
        (
            [HANDLE] => 3
            [Z_GRUPO] => 
            [EMPRESA] => 1
            [FILIAL] => 1
            [DATAINICIO] => 2018-03-01
            [CONSUMO] => 3
            [VEICULO] => 82
        )

    [3] => Array
        (
            [HANDLE] => 4
            [Z_GRUPO] => 
            [EMPRESA] => 1
            [FILIAL] => 1
            [DATAINICIO] => 2018-02-01
            [CONSUMO] => 3.5
            [VEICULO] => 102
        )

)

Question:

I would like to search the Array with a DATA and VEHICLE as a reference.

Example:

What is the CONSUMPTION of VEICULO 82 in DATA 10/02/2018 ?

If it were a database, it would simply be this:

SELECT TOP 1 * FROM VEICULOCONSUMO
WHERE VEICULO = 82
AND DATAINICIO <= '10/02/2018'
ORDER BY DATAINICIO DESC

The correct return would be: 2.5

Since the record was made in 10/02/2018 , then the most recent or last date was [1][DATAINICIO] => 2018-02-01 .

The "X" of the question is how to pull CONSUMPTION referring to DATE and VEHICLE, where the DATA is equal to DATAINICIO or the previous one .

    
asked by anonymous 20.07.2018 / 19:58

1 answer

1

You can get records that have a vehicle equal to 82 and start date less than or equal to 2018-02-10 with the array_filter function:

$filtrados = array_filter($registros, function ($registro) {
    return ($registro['VEICULO'] == 82) and ($registro['DATAINICIO'] <= '2018-02-10');
});

Sort result by start date, from highest to lowest:

usort($filtrados, function ($a, $b) {
    return $a['DATAINICIO'] <=> $b['DATAINICIO'];
});

And as you just want a record, get the last value from the array:

$final = array_pop($filtrados);
print_r($final);

Getting:

Array
(
    [HANDLE] => 2
    [Z_GRUPO] => 1
    [EMPRESA] => 1
    [FILIAL] => 1
    [DATAINICIO] => 2018-02-01
    [CONSUMO] => 2.5
    [VEICULO] => 82
)

What is the most recent record, dated less than or equal to 2018-02-10.

    
20.07.2018 / 20:21