PHP:如何使用Array_filter()来过滤数组键?中的回调函数array_filter()只传递数组的值,而不是键。如果我有:$my_array = array("foo" => 1, "hello" => "world");$allowed = array("foo", "bar");删除所有键的最佳方法是什么$my_array不在$allowed阵列?期望产出:$my_array = array("foo" => 1);
3 回答
慕容森
TA贡献1853条经验 获得超18个赞
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
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']
缥缈止盈
TA贡献2041条经验 获得超4个赞
array_intersect_key
array_flip
:
var_dump(array_intersect_key($my_array, array_flip($allowed)));array(1) { ["foo"]=> int(1)}
慕神8447489
TA贡献1780条经验 获得超1个赞
array_filter
// Filter out array elements with keys shorter than 4 characters$a = array( 0 => "val 0", "one" => "val one", "two" => "val two", "three"=> "val three", "four" => "val four", "five" => "val five", "6" => "val 6"); $f = array_filter(array_keys($a), function ($k){ return strlen($k)>=4; }); $b = array_intersect_key($a, array_flip($f));print_r($b);
Array( [three] => val three [four] => val four [five] => val five)
- 3 回答
- 0 关注
- 1087 浏览
添加回答
举报
0/150
提交
取消