好的我在PHP中有这种关联数组
$arr = array(
"fruit_aac" => "apple",
"fruit_2de" => "banana",
"fruit_ade" => "grapes",
"other_add" => "sugar",
"other_nut" => "coconut",
);
现在我想要的是只选择以键fruit_
开头的元素。怎么可能这样呢?我可以使用正则表达式吗?或任何PHP数组函数可用?有没有解决方法?请举例说明您的解决方案
答案 0 :(得分:5)
$fruits = array();
foreach ($arr as $key => $value) {
if (strpos($key, 'fruit_') === 0) {
$fruits[$key] = $value;
}
}
答案 1 :(得分:3)
一种解决方案如下:
foreach($arr as $key => $value){
if(strpos($key, "fruit_") === 0) {
...
...
}
}
===确保在位置0找到字符串,因为如果找不到字符串,strpos也可以返回FALSE。
答案 2 :(得分:3)
你试试看:
function filter($var) {
return strpos($var, 'fruit_') !== false;
}
$arr = array(
"fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
print_r(array_flip(array_filter(array_flip($arr), 'filter')));
答案 3 :(得分:2)
如果您想尝试正则表达式,那么您可以尝试下面给出的代码......
$arr = array("fruit_aac"=>"apple",
"fruit_2de"=>"banana",
"fruit_ade"=>"grapes",
"other_add"=>"sugar",
"other_nut"=>"coconut",
);
$arr2 = array();
foreach($arr AS $index=>$array){
if(preg_match("/^fruit_.*/", $index)){
$arr2[$index] = $array;
}
}
print_r($arr2);
我希望它会对你有所帮助。
感谢