我想通过密钥的文本过滤数组。
假设我有一个像:
这样的数组Array
(
[FAR] =>
[NEAR] => 1
[IMMEDIATE] =>
[FAR_beacon_location] =>
[FAR_test] =>
[FAR_test2] =>
[NEAR_test] => 6
[NEAR_test2] => 6
)
从这个数组我只想要键的文本以NEAR
开头的元素。
我该怎么做?
答案 0 :(得分:6)
试试这段代码。
$res_arr = array();
foreach($my_array as $key=>$val) {
if(strpos($key, "NEAR") === 0) {
//Key matches,
$res_arr[] = $val;
}
}
print_r($res_arr);
答案 1 :(得分:1)
这样做..
<?php
$arr=Array
(
'FAR' => '',
'NEAR' => 1,
'IMMEDIATE' =>'',
'FAR_beacon_location' =>'',
'FAR_test' => '',
'FAR_test2' =>'',
'NEAR_test' => 6,
'NEAR_test2' => 6
);
foreach($arr as $k=>$v)
{
if(substr($k, 0, 4)!='NEAR')
{
unset($arr[$k]);
}
}
echo "<pre>";
print_r($arr);
输出:
Array
(
[NEAR] => 1
[NEAR_test] => 6
[NEAR_test2] => 6
)
答案 2 :(得分:1)
function is_NEAR($var)
{
return strpos($var, "NEAR") === 0;
}
print_r(array_flip(array_filter(array_flip($arr), "is_NEAR")));
答案 3 :(得分:-1)
$array=Array
(
[FAR] =>
[NEAR] => 1
[IMMEDIATE] =>
[FAR_beacon_location] =>
[FAR_test] =>
[FAR_test2] =>
[NEAR_test] => 6
[NEAR_test2] => 6
)
foreach($array as $key=>$value)
{
if(strpos($key,"NEAR")==0)
{
// do your task
}
}