Home > Net >  filter multidimensional array by value
filter multidimensional array by value

Time:01-13

I have the following array:

$entrate=Array
(
    0 => Array(
            'id' => 1,
            'nome' => 'Stipendio',
            'datamov' => '2023-04-15',
            'mese' => 4,
            'anno' => 2023,
            'total_mov' => 3000.00
        ),

    1 => Array(
            'id' => 1,
            'nome' => 'Stipendio',
            'datamov' => '2023-03-15',
            'mese' => 3,
            'anno' => 2023,
            'total_mov' => 3000.00
        ),

    2 => Array(
            'id' => 1,
            'nome' => 'Stipendio',
            'datamov' => '2023-02-15',
            'mese' => 2,
            'anno' => 2023,
            'total_mov' => 3000.00
        ),

    3 => Array(
            'id' => 1,
            'nome' => 'Stipendio',
            'datamov' => '2023-01-15',
            'mese' => 1,
            'anno' => 2023,
            'total_mov' => 3000.00
        ),

    4 => Array(
            'id' => 4,
            'nome' => 'Interessi Attivi',
            'datamov' => '',
            'mese' => '',
            'anno' => '',
            'total_mov' => 'VUOTO'
        )

);

Starting from this I want to be able to select a specific 'nome' and filter the array to return just the items of this array that match that 'nome'. So for example if I want to filter by 'Stipendio' I'll get the first three elements only. If I filter by 'Interessi Attivi' just the fourth. If I filter by 'some other key' I'll get an empty array.

I was trying to use

$tipo_mov='Stipendio';
$entrata = array_filter($entrate, function ($value) use ($tipo_mov) {

    return ($entrate[$key]['nome'] == $tipo_mov);

});

but I cannot shape it so that it'll give me back the expected filtering (this code is not running obviously and throwing a bunch of errors).

What am I missing?

CodePudding user response:

$value in array_filter() are the inner arrays of $entrate, so you want to search for a match on $value['nome']:

https://paiza.io/projects/BmEdekWY8elJ90rIPjTGGQ

$tipo_mov='Stipendio'; 

$entrata = array_filter($entrate, function ($value) use ($tipo_mov) 
{
    return $value['nome'] == $tipo_mov;

});

print_r($entrata);
  • Related