查找具有特定键名前缀的数组元素

时间:2015-05-29 17:07:27

标签: php arrays

我有一个包含大量元素的关联数组,并且希望获得具有带有特定前缀的键名的所有元素的列表。

示例:

$arr = array(
  'store:key' => 1,
  'user' => 'demo',
  'store:foo' => 'bar',
  'login' => true,
);

// this is where I need help with:
// the function should return only elements with a key that starts with "store:"
$res = list_values_by_key( $arr, 'store:' );

// Desired output:
$res = array(
  'store:key' => 1,
  'store:foo' => 'bar',
);

3 个答案:

答案 0 :(得分:1)

这应该适合你:

只需从您的阵列中获取以store:开头的<?php $arr = array( 'store:key' => 1, 'user' => 'demo', 'store:foo' => 'bar', 'login' => true, ); $result = array_intersect_key($arr, array_flip(preg_grep("/^store:/", array_keys($arr)))); print_r($result); ?> 所有键。然后进行简单的preg_grep()调用以获得两个数组的交叉。

Array
(
    [store:key] => 1
    [store:foo] => bar
)

输出:

- (IBAction)scanCard:(id)sender {
  CardIOPaymentViewController *scanViewController = [[CardIOPaymentViewController alloc] initWithPaymentDelegate:self];
  [self presentViewController:scanViewController animated:YES completion:nil];
}

答案 1 :(得分:1)

你可以这样做:

$arr = array(
  'store:key' => 1,
  'user' => 'demo',
  'store:foo' => 'bar',
  'login' => true,
);

$arr2 = array();
foreach ($arr as $array => $value) {
    if (strpos($array, 'store:') === 0) {
        $arr2[$array] = $value;
    }
}
var_dump($arr2);

返回:

array (size=2)
'store:key' => int 1
'store:foo' => string 'bar' (length=3)

答案 2 :(得分:0)

从php 5.6开始,您可以使用array_filter

$return = array_filter($array, function ($e) {
        return strpos($e, 'store:') === 0;
}, ARRAY_FILTER_USE_KEY);

var_dump($return);

对于早期版本,您可以使用

$return = array_intersect_key($array, array_flip(array_filter(array_keys($array), function ($e) {
    return strpos($e, 'store:') === 0;
})));

Demo