开发者

Get part of an array

开发者 https://www.devze.com 2022-12-17 06:27 出处:网络
I have an array: $array = array( \'key1\' => \'value1\', \'key2\' => \'value2\', \'key3\' => \'value3\',

I have an array:

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

and I would like to get a part of it with specified keys - for example key2, key4, key5.

Expected result:

$result = array(
  'key2' => 'value2',
  'key4' => 'value4',
  'key5'开发者_开发技巧 => 'value5',
);

What is the fastest way to do it ?


You need array_intersect_key function:

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

Also array_flip can help if your keys are in array as values:

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


You can use array_intersect_key and array_fill_keys to do so:

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

array_flip instead of array_fill_keys will also work:

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


Only way I see is to iterate the array and construct a new one.

Either walk the array with array_walk and construct the new one or construct a matching array and use array_intersect_key et al.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号