仅获取具有某些键的数组元素 [英] Get only the array elements with certain keys
本文介绍了仅获取具有某些键的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
阵列键上的模式匹配
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"
);
我需要所有带有包含字符串special_
的键的元素.这些应该定义一个新的数组:
I would need all elements with a key containing the string special_
. These should define a new array:
$special_items = array(
"special_1" => "3",
"special_2" => "5",
"special_3" => "6",
);
除了while
循环外,还有一种聪明的方法吗?
Is there a smart method besides a while
loop?
推荐答案
如何?
$special_items = array();
foreach($items as $key => $val) {
if(substr($key, 0, 8) == 'special_')
$special_items[$key] = $val;
}
这篇关于仅获取具有某些键的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文