How to filter a dynamic multidimensional array?

0

I am new to PHP and am in need of help, how do I filter a dynamic multidimensional array by removing arrays that do not have a specific value?

Taking for example: In my code, I make a call in the database and create a dynamic array according to this structure.

Array


(  
  [0] => Array
        (
            [0] => Array
                (
                    [nome] => Maria
                    [idade] => 22
                )

            [1] => Array
                (
                    [casas_alugadas] => 'S' 
                     [qtd] => 10
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [nome] => Joao
                    [idade] => 28
                )

            [1] => Array
                (
                    [casas_alugadas] => 'N'
                )

        )

)

I need to filter based on the values, if the array has the element "homes_alugadas == N", it is deleted and passed to the next, leaving only the index array 0, as done in the example. How would you do that?

    
asked by anonymous 23.03.2018 / 15:53

1 answer

0

You can use the array_filter function. Just pass the array you want to filter and a function to perform the condition. In this function you can return true to return array or false to "skip" the array and check the next.

Example:

<?php

$arr = [
    [
        [
            "nome"  => "Maria",
            "idade" => 22
        ],
        [
            "casas_alugadas" => "S",
            "qtd" => 10
        ]
    ],
    [
        [
            "nome" => "João",
            "idade" => 28
        ],
        [
            "casas_alugadas" => "N"
        ]
    ]
];

/* Percorre todos os índices */
$arr = array_filter($arr, function($item) {

    /**
     * Verifica se o índice 'casas_alugadas' existe no
     * índice 1 e se o valor é diferente de "N"
     */
    return $item[1]["casas_alugadas"] != "N";
});

var_dump($arr);

Demo: link

If you do not know the index, just use the example below:

<?php

$arr = [
    [
        [
            "nome"  => "Maria",
            "idade" => 22
        ],
        [
            "casas_alugadas" => "S",
            "qtd" => 10
        ]
    ],
    [
        [
            "nome" => "João",
            "idade" => 28
        ],
        [
            "casas_alugadas" => "N"
        ]
    ]
];


/* Filtra os dados do array */
$arr = array_filter($arr, function($item) {

    /* Percorre todos os índices */
    foreach($item as $result) {

        /**
         * Verifica se existe o índice 'casas_alugadas' e se o valor dele é "S"
         * Caso a condição seja verdadeira, valida e retorna o array
         */
        if (isset($result['casas_alugadas']) && $result['casas_alugadas'] == "S") {
            return true;
        }
    }
});

var_dump($arr);

Demo: link     

23.03.2018 / 16:12