[英]How to filter any array by key text(name)?
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
. 从这个数组中,我只需要其键的文本以
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.