PHP 脚本用于从以特定字符串开头的数组中获取全部键
方法 1
$arr_main_array = array('test_val' => 123, 'other-value' => 456, 'test_result' => 789);
foreach($arr_main_array as $key => $value){
$exp_key = explode('-', $key);
if($exp_key[0] == 'test'){
$arr_result[] = $value;
}
}
if(isset($arr_result)){
print_r($arr_result);
}方法 2
A functional approach
An array_filter_key type of function is taken, and applied to the array elements
$array = array_filter_key($array, function($key) {
return strpos($key, 'foo-') === 0;
});方法 3
一种过程化方法 −
$val_1 = array();
foreach ($array as $key => $value) {
if (strpos($key, 'foo-') === 0) {
$val_1[$key] = $value;
}
}方法 4
使用对象的过程化方法 −
示例
$i = new ArrayIterator($array);
$val_1 = array();
while ($i->valid()) {
if (strpos($i->key(), 'foo-') === 0) {
$val_1[$i->key()] = $i->current();
}
$i->next();
}输出
这将产生以下输出 −
Array(test_val => 123 test_result => 789)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP