php 仅获取具有特定键的数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12887322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get only the array elements with certain keys
提问by Steeven
Possible Duplicate:
Pattern Match on a Array Key
可能的重复:
数组键上的模式匹配
I need to get all the elements in an array with a specific key pattern. For example in this array:
我需要使用特定的键模式获取数组中的所有元素。例如在这个数组中:
$items = array(
"a" => "1",
"b" => "2",
"special_1" => "3",
"c" => "4",
"special_2" => "5",
"special_3" => "6",
"d" => "7"
);
I would need all elements with a key containing the string special_. These should define a new array:
我需要所有带有包含字符串的键的元素special_。这些应该定义一个新数组:
$special_items = array(
"special_1" => "3",
"special_2" => "5",
"special_3" => "6",
);
Is there a smart method besides a whileloop?
除了while循环,还有没有聪明的方法?
回答by Austin Brunkhorst
How about this?
这个怎么样?
$special_items = array();
foreach($items as $key => $val) {
if(substr($key, 0, 8) == 'special_')
$special_items[$key] = $val;
}
回答by Niet the Dark Absol
First you need to get an array containing the keys. array_keys
首先,您需要获取一个包含键的数组。 array_keys
Then, you need to filter the keys to find the ones you want. array_filter
然后,您需要过滤键以找到所需的键。 array_filter
Use this callback:
使用这个回调:
function($a) {return substr($a,0,8) == "special_";}
Then flip the array so that the keys are keys again instead of values. array_flip
然后翻转数组,使键再次成为键而不是值。 array_flip
Finally, intersect those keys with the original array. array_intersect_key
最后,将这些键与原始数组相交。 array_intersect_key
Result:
结果:
$special_items = array_intersect_key($items,array_flip(array_filter(array_keys($items),function($a) {return substr($a,0,8) == "special_";})));
回答by Baba
You can use FilterIterator
您可以使用 FilterIterator
$iterator = new SpecialFilter($items, 'special');
var_dump(iterator_to_array($iterator));
Output
输出
array
'special_1' => string '3' (length=1)
'special_2' => string '5' (length=1)
'special_3' => string '6' (length=1)
Class Used
使用的类
class SpecialFilter extends FilterIterator {
private $f;
public function __construct(array $items, $filter) {
$object = new ArrayObject( $items );
$this->f = $filter;
parent::__construct( $object->getIterator() );
}
public function accept() {
return 0 === strpos( $this->getInnerIterator()->key(), $this->f );
}
}
回答by goat
$special_items = array_intersect_key(array_flip(preg_grep('/^special_\d+/', array_keys($items))), $items);
Please don't actually use that. Just use a foreach loop with strpos + an if statement like all normal people would.
请不要实际使用它。只需像所有普通人一样使用带有 strpos + if 语句的 foreach 循环即可。
回答by Seth
how about
怎么样
$keys = preg_grep( "/special_/i", array_keys( $items ) );
$new_array = array();
foreach( $keys as $k )
{
$new_array[ $k ] = $items[ $k ];
}

