如何用键的一部分过滤数组?
我有一个这样的阵列:如何用键的一部分过滤数组?
Array([id-1] => N
[nm-1] => my_val_01;
[id-48] => S
[nm-48] => my_val_02;
[id-52] => N
[nm-52] => my_val_03;
[id-49] => N
[nm-49] => my_val_04;
[id-50] => N
[nm-50] => my_val_05;
}
并想通过键的一部分进行过滤。在这种情况下,我想有有“ID-”所有钥匙,并导致本:
Array([id-1] => N
[id-48] => S
[id-52] => N
[id-49] => N
[id-50] => N
}
谁能帮助?
回答:
foreach (array_keys($array) as $key) { if (!preg_match('/^id-\d+/', $key)) {
unset($array[$key]);
}
}
回答:
尝试用:
$input = array(/* your data */); $output = array();
$pattern = 'id-';
foreach ($input as $key => $value) {
if (strpos($key, $pattern) === 0) { # Use identical not equal operator here
$output[$key] = $value;
}
}
回答:
这样你可以做。
$arr = Array([id-1] => N
[nm-1] => my_val_01;
[id-48] => S
[nm-48] => my_val_02;
[id-52] => N
[nm-52] => my_val_03;
[id-49] => N
[nm-49] => my_val_04;
[id-50] => N
[nm-50] => my_val_05;
};
$new = array();
foreach($arr as $key => $value){
if(stripos($key, "id-") !== false){
$new[$key] = $value;
}
}
//so $new is your required array here
回答:
使用以下(未经测试):
function filter($key) { return substr($key, 0, 3) == 'id-';
}
$keys = array_filter(array_keys($array), 'filter');
if(empty($keys))
$array = array();
else
$array = array_intersect_key(array_flip($keys), $input);
回答:
你可以写一个小功能,工程模拟array_filter:
<?php $a = array(
'id-1' => 'N', 'nm-1' => 'my_val_01', 'id-48' => 'S', 'nm-48' => 'my_val_02', 'id-52' => 'N',
'nm-52' => 'my_val_03', 'id-49' => 'N', 'nm-49' => 'my_val_04', 'id-50' => 'N', 'nm-50' => 'my_val_05'
);
$b = array_filter_key($a, function($e) {
return 0===strpos($e, 'id-');
});
var_dump($b);
function array_filter_key($source, $callback) {
// TODO: check arguments
$keys = array_keys($source);
$keys = array_filter($keys, $callback);
return (0===count($keys)) ?
array()
:
array_intersect_key(array_flip($keys), $source)
;
}
打印
array(5) { ["id-1"]=>
int(0)
["id-48"]=>
int(2)
["id-52"]=>
int(4)
["id-49"]=>
int(6)
["id-50"]=>
int(8)
}
回答:
答案,上互联网,利用array_intersect_key是不正确的。 它们正确过滤,但输出“过滤的键索引”值而不是输入数组值。
这里是一个固定的版本
/** * Filter array keys by callback
*
* @param array $input
* @param $callback
* @return NULL|unknown|multitype:
*/
function array_filter_keys($input, $callback)
{
if (!is_array($input)) {
trigger_error('array_filter_key() expects parameter 1 to be array, ' . gettype($input) . ' given', E_USER_WARNING);
return null;
}
if (empty($input)) {
return $input;
}
$filteredKeys = array_filter(array_keys($input), $callback);
if (empty($filteredKeys)) {
return array();
}
$input = array_intersect_key($input, array_flip($filteredKeys));
return $input;
}
回答:
如果您正在使用最新版本的PHP:
$filtered_arr = array_filter($arr, 'filter_my_array', ARRAY_FILTER_USE_KEY); function filter_my_array($key) {
return preg_match("/^id-\d+/", $key);
}
以上是 如何用键的一部分过滤数组? 的全部内容, 来源链接: utcz.com/qa/260855.html