2011-12-28 44 views
4

考慮:使用數組的鍵創建新陣列

$keys = array("some", "thing", "rand", "keys"); 

我想返回一個數組:

$data = array(
    "some" => "163", 
    "rand" => "630", 
    "om" => "43", 
    "words" => "924", 
    "as" => "4", 
    "keys" => "54" 
); 

我使用僅符合某些按鍵,該按鍵想要一個新的數組與普通的鑰匙,創造:

$arr = array(
    "some" => "163", 
    "rand" => "630", 
    "keys" => "54" 
); 

回答

7

您可以array_intersect_key()array_flip()做到這一點:

$arr = array_intersect_key($data, array_flip($keys)); 

結果:

 
Array 
(
    [some] => 163 
    [rand] => 630 
    [keys] => 54 
) 
0
$result = array_intersect_key($data, array_flip($keys)); 
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);