慕容森
PHP 5.6引入了第三个参数array_filter(), flag,您可以设置为ARRAY_FILTER_USE_KEY按键而不是值过滤:$my_array = ['foo' => 1, 'hello' => 'world'];$allowed = ['foo', 'bar'];$filtered = array_filter(
$my_array,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY);显然这不像array_intersect_key($my_array, array_flip($allowed)),但它确实提供了对密钥执行任意测试的额外灵活性。$allowed可以包含regex模式而不是普通字符串。您也可以使用ARRAY_FILTER_USE_BOTH将值和键传递给筛选函数。下面是一个基于第一个示例的人为示例,但请注意,我不建议使用$allowed这样:$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];$allowed = ['foo' => true, 'bar' => true, 'hello' => 'world'];$filtered = array_filter(
$my_array,
function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
return isset($allowed[$key]) && (
$allowed[$key] === true || $allowed[$key] === $val );
},
ARRAY_FILTER_USE_BOTH); // ['foo' => 1, 'bar' => 'baz']