PHP: ¿Cómo usar array filter () para filtrar claves de array?


La función de devolución de llamada en array_filter() solo pasa los valores de la matriz, no las claves.

Si tengo:

$my_array = array("foo" => 1, "hello" => "world");

$allowed = array("foo", "bar");

¿Cuál es la mejor manera de eliminar todas las claves en $my_array que no están en la matriz $allowed?

Salida deseada:

$my_array = array("foo" => 1);
 293
Author: Jeff Puckett, 2010-11-23

13 answers

PHP 5.6 introdujo un tercer parámetro para array_filter(), flag, que se puede configurar a ARRAY_FILTER_USE_KEY para filtrar por clave en lugar de valor:

$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed  = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);

Claramente esto no es tan elegante como array_intersect_key($my_array, array_flip($allowed)), pero ofrece la flexibilidad adicional de realizar una prueba arbitraria contra la clave, por ejemplo, $allowed podría contener patrones de expresiones regulares en lugar de cadenas simples.

También puede utilizar ARRAY_FILTER_USE_BOTH para que tanto el valor como la clave se pasen a su función de filtro. Aca un ejemplo artificial basado en el primero, pero tenga en cuenta que no recomendaría codificar reglas de filtrado usando $allowed de esta manera:

$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed  = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
    $my_array,
    function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
        return isset($allowed[$key]) && (
            $allowed[$key] === true || $allowed[$key] === $val
        );
    },
    ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']
 206
Author: Richard Turner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:32

Con array_intersect_key y array_flip:

var_dump(array_intersect_key($my_array, array_flip($allowed)));

array(1) {
  ["foo"]=>
  int(1)
}
 411
Author: Vincent Savard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-21 14:51:43

Necesitaba hacer lo mismo, pero con un array_filter más complejo en las teclas.

Así es como lo hice, usando un método similar.

// Filter out array elements with keys shorter than 4 characters
$a = array(
  0      => "val 0", 
  "one"  => "val one", 
  "two"  => "val two", 
  "three"=> "val three", 
  "four" => "val four", 
  "five" => "val five", 
  "6"    => "val 6"
); 

$f = array_filter(array_keys($a), function ($k){ return strlen($k)>=4; }); 
$b = array_intersect_key($a, array_flip($f));
print_r($b);

Esto produce el resultado:

Array
(
    [three] => val three
    [four] => val four
    [five] => val five
)
 39
Author: Christopher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-25 20:02:18

Aquí hay una solución más flexible usando un cierre:

$my_array = array("foo" => 1, "hello" => "world");
$allowed = array("foo", "bar");
$result = array_flip(array_filter(array_flip($my_array), function ($key) use ($allowed)
{
    return in_array($key, $allowed);
}));
var_dump($result);

Salidas:

array(1) {
  'foo' =>
  int(1)
}

Así que en la función, puede hacer otras pruebas específicas.

 8
Author: COil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-25 10:38:49

Si está buscando un método para filtrar una matriz por una cadena que ocurre en las claves, puede usar:

$mArray=array('foo'=>'bar','foo2'=>'bar2','fooToo'=>'bar3','baz'=>'nope');
$mSearch='foo';
$allowed=array_filter(
    array_keys($mArray),
    function($key) use ($mSearch){
        return stristr($key,$mSearch);
    });
$mResult=array_intersect_key($mArray,array_flip($allowed));

El resultado de print_r($mResult) es

Array ( [foo] => bar [foo2] => bar2 [fooToo] => bar3 )

Una adaptación de esta respuesta que soporta expresiones regulares

function array_preg_filter_keys($arr, $regexp) {
  $keys = array_keys($arr);
  $match = array_filter($keys, function($k) use($regexp) {
    return preg_match($regexp, $k) === 1;
  });
  return array_intersect_key($arr, array_flip($match));
}

$mArray = array('foo'=>'yes', 'foo2'=>'yes', 'FooToo'=>'yes', 'baz'=>'nope');

print_r(array_preg_filter_keys($mArray, "/^foo/i"));

Salida

Array
(
    [foo] => yes
    [foo2] => yes
    [FooToo] => yes
)
 4
Author: Nicolas Zimmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-02 20:05:07

Cómo obtener la clave actual de un array cuando se usa array_filter

Independientemente de cómo me guste la solución de Vincent para el problema de Maček, en realidad no usa array_filter. Si usted vino aquí desde un motor de búsqueda que tal vez en busca de algo como esto (PHP >= 5.3):

$array = ['apple' => 'red', 'pear' => 'green'];
reset($array); // Unimportant here, but make sure your array is reset

$apples = array_filter($array, function($color) use ($&array) {
  $key = key($array);
  next($array); // advance array pointer

  return key($array) === 'apple';
}

Pasa la matriz que está filtrando como una referencia a la devolución de llamada. Como array_filter no itera convencionalmente sobre la matriz al aumentar su puntero interno público, debe avanzar por a ti mismo.

Lo que es importante aquí es que necesita asegurarse de que su matriz se restablezca, de lo contrario podría comenzar justo en el medio de ella.

En PHP >= 5.4 podría hacer la devolución de llamada aún más corta:

$apples = array_filter($array, function($color) use ($&array) {
  return each($array)['key'] === 'apple';
}
 4
Author: flu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 09:42:12

Aquí hay una alternativa menos flexible usando unset():

$array = array(
    1 => 'one',
    2 => 'two',
    3 => 'three'
);
$disallowed = array(1,3);
foreach($disallowed as $key){
    unset($array[$key]);
}

El resultado de print_r($array) es:

Array
(
    [2] => two
)

Esto no es aplicable si desea mantener los valores filtrados para su uso posterior, pero más ordenados, si está seguro de que no lo hace.

 3
Author: Alastair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-31 03:50:40

A partir de PHP 5.6, puede usar el indicador ARRAY_FILTER_USE_KEY en array_filter:

$result = array_filter($my_array, function ($k) use ($allowed) {
    return in_array($k, $allowed);
}, ARRAY_FILTER_USE_KEY);


De lo contrario, puede usar esta función ( desde TestDummy):

function filter_array_keys(array $array, $callback)
{
    $matchedKeys = array_filter(array_keys($array), $callback);

    return array_intersect_key($array, array_flip($matchedKeys));
}

$result = filter_array_keys($my_array, function ($k) use ($allowed) {
    return in_array($k, $allowed);
});


Y aquí hay una versión aumentada de la mía, que acepta una devolución de llamada o directamente las teclas:

function filter_array_keys(array $array, $keys)
{
    if (is_callable($keys)) {
        $keys = array_filter(array_keys($array), $keys);
    }

    return array_intersect_key($array, array_flip($keys));
}

// using a callback, like array_filter:
$result = filter_array_keys($my_array, function ($k) use ($allowed) {
    return in_array($k, $allowed);
});

// or, if you already have the keys:
$result = filter_array_keys($my_array, $allowed));


Por último, pero no menos importante, también puede utilizar un simple foreach:

$result = [];
foreach ($my_array as $key => $value) {
    if (in_array($key, $allowed)) {
        $result[$key] = $value;
    }
}
 3
Author: Gras Double,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-17 12:49:44

Tal vez un exceso si lo necesita solo una vez, pero puede usar la biblioteca YaLinqo* para filtrar colecciones (y realizar cualquier otra transformación). Esta biblioteca permite peforming consultas tipo SQL en objetos con sintaxis fluida. Su where la función acepta un calback con dos argumentos: un valor y una clave. Por ejemplo:

$filtered = from($array)
    ->where(function ($v, $k) use ($allowed) {
        return in_array($k, $allowed);
    })
    ->toArray();

(La función where devuelve un iterador, por lo que si solo necesita iterar con foreach sobre la secuencia resultante una vez, ->toArray() puede ser quitar.)

* desarrollado por mí

 1
Author: Athari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-04 00:19:55

Con esta función puede filtrar un array multidimensional

function filter_array_keys($array,$filter_keys=array()){

    $l=array(&$array);
    $c=1;
    //This first loop will loop until the count var is stable//
    for($r=0;$r<$c;$r++){
        //This loop will loop thru the child element list//
        $keys = array_keys($l[$r]);

        for($z=0;$z<count($l[$r]);$z++){
            $object = &$l[$r][$keys[$z]];

            if(is_array($object)){
                $i=0;
                $keys_on_array=array_keys($object);
                $object=array_filter($object,function($el) use(&$i,$keys_on_array,$filter_keys){
                    $key = $keys_on_array[$i];
                    $i++;

                    if(in_array($key,$filter_keys) || is_int($key))return false;                
                    return true;                        
                });
            }

            if(is_array($l[$r][$keys[$z]])){
                $l[] = &$l[$r][$keys[$z]];
                $c++;
            }//IF           
        }//FOR
    }//FOR  

    return $l[0];

}
 0
Author: user1220713,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-15 09:41:44

Función de filtro de matriz de php:

array_filter ( $array, $callback_function, $flag )

Array array-Es el array de entrada

Call callback_function - La función callback a usar, Si la función callback devuelve true, el valor actual de la matriz se devuelve en la matriz de resultados.

Flag flag - Es parámetro opcional, determinará qué argumentos se envían a la función callback. Si este parámetro está vacío, la función callback tomará los valores de la matriz como argumento. Si desea enviar clave de matriz como argumento entonces use {flag como ARRAY_FILTER_USE_KEY . Si desea enviar ambas claves y valores, debe usar {flag como ARRAY_FILTER_USE_BOTH .

Por Ejemplo : Considere la matriz simple

$array = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);

Si desea filtrar el array basado en la clave array, necesitamos usar ARRAY_FILTER_USE_KEY como tercer parámetro de la función array array_filter.

$get_key_res = array_filter($array,"get_key",ARRAY_FILTER_USE_KEY );

Si desea filtrar la matriz basada en la clave de matriz y la matriz valor , Necesitamos usar ARRAY_FILTER_USE_BOTH como tercer parámetro de la función array array_filter.

$get_both = array_filter($array,"get_both",ARRAY_FILTER_USE_BOTH );

Funciones de devolución de llamada de ejemplo:

 function get_key($key)
 {
    if($key == 'a')
    {
        return true;
    } else {
        return false;
    }
}
function get_both($val,$key)
{
    if($key == 'a' && $val == 1)
    {
        return true;
    }   else {
        return false;
    }
}

Saldrá

Output of $get_key is :Array ( [a] => 1 ) 
Output of $get_both is :Array ( [a] => 1 ) 
 0
Author: prince jose,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-11 03:14:07

/ / Filtrar elementos de matriz con claves más cortas que 4 caracteres // Mediante el uso de la función Anónima con cierre...

function comparison($min)
{
   return function($item) use ($min) { 
      return strlen($item) >= $min;   
   }; 
}

$input = array(
  0      => "val 0",
  "one"  => "val one",
  "two"  => "val two",
  "three"=> "val three",
  "four" => "val four",  
  "five" => "val five",    
  "6"    => "val 6"    
);

Output output = array_filter (array_keys(input input), comparison (4));

Print_r (output output);
introduzca la descripción de la imagen aquí

 0
Author: ZOB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-24 12:53:47
$elements_array = ['first', 'second'];

Función para eliminar algunos elementos del array

function remove($arr, $data) {
    return array_filter($arr, function ($element) use ($data) {
        return $element != $data;
    });
}

Llamar e imprimir

print_r(remove($elements_array, 'second'));

El resultado Array ( [0] => first )

 0
Author: Abdallah Awwad Alkhwaldah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-24 08:02:24