PHP array array

1

I have a PHP array, as illustrated below. I know I can filter them by traversing them ( foreach , for example) and seeing if a value meets a certain criterion. But is there any simpler and faster way to do this filter?

<?php
$clientes = [
   ['id' => 1, 'nome' => 'Alefe', 'valor_autorizado' => 12159.99],
   ['id' => 2, 'nome' => 'Bete', 'valor_autorizado' => 35122.00],
   ['id' => 3, 'nome' => 'Guimel', 'valor_autorizado' => 86242.90]
   ['id' => 4, 'nome' => 'Dalete', 'valor_autorizado' => 2342.31]
];

For example, I want all customers with an authorized value greater than $ 40,000.

    
asked by anonymous 14.03.2018 / 21:12

1 answer

3

Yes. You can use the array_filter function. With this function you need to pass an array and a callback function that will be responsible for returning true or false . In this function you can put your condition, for example:

<?php

$clientes = [
   ['id' => 1, 'nome' => 'Alefe', 'valor_autorizado' => 12159.99],
   ['id' => 2, 'nome' => 'Bete', 'valor_autorizado' => 35122.00],
   ['id' => 3, 'nome' => 'Guimel', 'valor_autorizado' => 86242.90],
   ['id' => 3, 'nome' => 'Juimel', 'valor_autorizado' => 86242.90],
   ['id' => 4, 'nome' => 'Dalete', 'valor_autorizado' => 2342.31]
];

/* Valor acima de 40.000 */
$clientes_filtrados = array_filter($clientes, function($arr) {
    return $arr["valor_autorizado"] >= 40000;
});

var_dump($clientes_filtrados);

/* Valor acima de 40.000 e que começa com a letra G */
$clientes_filtrados = array_filter($clientes, function($arr) {
    return $arr["valor_autorizado"] >= 40000 && preg_match("/^G/", $arr["nome"]);
});

var_dump($clientes_filtrados);

Demo at IdeOne

    
14.03.2018 / 21:17