我正在尝试确定基于模式的数组中是否存在匹配或匹配,
数组的一个例子:
Array
(
[author_id] => 1
[channel_id] => 1
[site_id] => 1
[entry_id] => 6
[url_title] => test_title_with_file2
[title] => Test Title with file
[field_id_1_directory] => 1
[field_id_4_directory] => 1
[submit] => Submit
[entry_date] => 1278219110
)
我想确定 field_id_x_directory 键或键是否存在,如果存在,则循环遍历每个键并运行一个将'x'用作变量的函数。< / p>
非常感谢,
伊恩。
答案 0 :(得分:11)
foreach (array_keys($arr) as $k) {
if (preg_match('/^field_id_(\\d+)_directory$/', $k, $matches)) {
//do sth with $arr[$k] and $matches[1]
}
}
答案 1 :(得分:1)
更好的选择是:
function preg_grep_keys( $pattern, $input, $flags = 0 )
{
$keys = preg_grep( $pattern, array_keys( \$input ), \$flags );
$vals = array();
foreach ( $keys as $key )
{
$vals[$key] = $input[$key];
}
return $vals;
}
答案 2 :(得分:1)
$input = array (
'hello'=>2,
'hello stackoverflow'=>1,
'hello world',
'foo bar bas'=>4
);
$matches = preg_grep ('/^hello$/i', array_keys($input));
echo $input[$matches[0]];
将返回2