I want to filter array by the key's text.
Suppose I have an array like:
Array
(
[FAR] =>
[NEAR] => 1
[IMMEDIATE] =>
[FAR_beacon_location] =>
[FAR_test] =>
[FAR_test2] =>
[NEAR_test] => 6
[NEAR_test2] => 6
)
From this array I just want the elements whose key's text starts with NEAR
.
How do I do that?
try this code.
$res_arr = array();
foreach($my_array as $key=>$val) {
if(strpos($key, "NEAR") === 0) {
//Key matches,
$res_arr[] = $val;
}
}
print_r($res_arr);
Do like this..
<?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);
OUTPUT :
Array
(
[NEAR] => 1
[NEAR_test] => 6
[NEAR_test2] => 6
)
function is_NEAR($var)
{
return strpos($var, "NEAR") === 0;
}
print_r(array_flip(array_filter(array_flip($arr), "is_NEAR")));
$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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.