2010-01-25 11 views
7

tengo una matriz:Obtener parte de una matriz

$array = array(
    'key1' => 'value1', 
    'key2' => 'value2', 
    'key3' => 'value3', 
    'key4' => 'value4', 
    'key5' => 'value5', 
); 

y me gustaría obtener una parte de ella con claves especificadas - por ejemplo key2, key4, key5.

Resultado esperado:

$result = array(
    'key2' => 'value2', 
    'key4' => 'value4', 
    'key5' => 'value5', 
); 

¿Cuál es la manera más rápida de hacerlo?

+1

víctima: http://stackoverflow.com/questions/1742018/somewhat -simple-php-array-intersection-question – SilentGhost

Respuesta

16

Usted necesita array_intersect_key función:

$result = array_intersect_key($array, array('key2'=>1, 'key4'=>1, 'key5'=>1)); 

también array_flip puede ayudar si las llaves están en matriz como valores:

$result = array_intersect_key(
    $array, 
    array_flip(array('key2', 'key4', 'key5')) 
); 
0

La única forma que veo es iterar la matriz y construir uno nuevo .

O recorra la matriz con array_walk y construya la nueva o construya una matriz que coincida y use array_intersect_key et al.

5

Puede utilizar array_intersect_key y array_fill_keys para hacerlo:

$keys = array('key2', 'key4', 'key5'); 
$result = array_intersect_key($array, array_fill_keys($keys, null)); 

array_flip en lugar de array_fill_keys también funcionará:

$keys = array('key2', 'key4', 'key5'); 
$result = array_intersect_key($array, array_flip($keys)); 
Cuestiones relacionadas