可能重复:
数组键上的模式匹配
我需要使用特定的键模式获取数组中的所有元素.例如在这个数组中:
$items = array(
"a" => "1",
"b" => "2",
"special_1" => "3",
"c" => "4",
"special_2" => "5",
"special_3" => "6",
"d" => "7"
);
Run Code Online (Sandbox Code Playgroud)
我需要所有带有包含字符串的键的元素special_
.这些应该定义一个新的数组:
$special_items = array(
"special_1" => "3",
"special_2" => "5",
"special_3" => "6",
);
Run Code Online (Sandbox Code Playgroud)
除了while
循环之外还有一种智能方法吗?
Aus*_*rst 22
这个怎么样?
$special_items = array();
foreach($items as $key => $val) {
if(substr($key, 0, 8) == 'special_')
$special_items[$key] = $val;
}
Run Code Online (Sandbox Code Playgroud)
首先,您需要获取包含键的数组. array_keys
然后,您需要过滤键以找到您想要的键. array_filter
使用此回调:
function($a) {return substr($a,0,8) == "special_";}
Run Code Online (Sandbox Code Playgroud)
然后翻转数组,使键再次成为键而不是值. array_flip
最后,将这些键与原始数组相交. array_intersect_key
结果:
$special_items = array_intersect_key($items,array_flip(array_filter(array_keys($items),function($a) {return substr($a,0,8) == "special_";})));
Run Code Online (Sandbox Code Playgroud)
您可以使用FilterIterator
$iterator = new SpecialFilter($items, 'special');
var_dump(iterator_to_array($iterator));
Run Code Online (Sandbox Code Playgroud)
输出
array
'special_1' => string '3' (length=1)
'special_2' => string '5' (length=1)
'special_3' => string '6' (length=1)
Run Code Online (Sandbox Code Playgroud)
使用类别
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31954 次 |
最近记录: |