假设:
$data = array(
"some" => "163",
"rand" => "630",
"om" => "43",
"words" => "924",
"as" => "4",
"keys" => "54"
);
我想要一个只使用与那些特定键匹配的键的新数组:
$keys = array( "some", "thing", "rand", "keys" );
我想返回一个包含这些键的数组,创建:
$arr = array(
"some" => "163",
"rand" => "630",
"keys" => "54"
);
答案 0 :(得分:7)
您可以使用array_intersect_key()
和array_flip()
执行此操作:
$arr = array_intersect_key($data, array_flip($keys));
结果:
Array ( [some] => 163 [rand] => 630 [keys] => 54 )
答案 1 :(得分:1)
$filteredArray = array_intersect_key($data, array_flip($keys));
是最简单的解决方案,
但只是为了与众不同:
$data = array(
"some" => "163",
"rand" => "630",
"om" => "43",
"words" => "924",
"as" => "4",
"keys" => "54"
);
$keys = array( "some", "thing", "rand", "keys" );
$filteredArray = array_filter($data,function($item) use (&$data,$keys) { $retVal = false; if (in_array(key($data),$keys)) $retVal = true; next($data); return $retVal; });
var_dump($filteredArray);
答案 2 :(得分:0)
$result = array_intersect_key($data, array_flip($keys));