2017-10-20 51 views
-2

在PHP中只有一個數組中的選定鍵及其值的最簡單方法是什麼? 舉例來說,如果我有一個數組:PHP - 只用現有數組中的選定鍵創建新陣列

$meta = [ 
     "nickname" => [ 
     0 => "John" 
     ] 
     "first_name" => [ 
     0 => "John" 
     ] 
     "last_name" => [ 
     0 => "Doe" 
     ] 
     "description" => array:1 [ 
     0 => "" 
     ] 
     "rich_editing" => [ 
     0 => "true" 
     ] 
     "comment_shortcuts" => [ 
     0 => "false" 
     ] 
     "admin_color" => [ 
     0 => "fresh" 
     ] 
     "use_ssl" => array:1 [ 
     0 => "0" 
     ] 
     "show_admin_bar_front" => [ 
     0 => "true" 
     ] 
     "locale" => [ 
     0 => "" 
     ] 
     "wp_capabilities" => [ 
     0 => "a:1:{s:10:"subscriber";b:1;}" 
     ] 
     "wp_user_level" => [ 
     0 => "0" 
     ] 
     "dismissed_wp_pointers" => [ 
     0 => "" 
     ] 
     "department" => [ 
     0 => "Administrasjon" 
     ] 
     "region" => [ 
     0 => "Oslo" 
     ] 
     "industry" => [ 
     0 => "Bane" 
     ] 
    ] 

什麼是獲得與例如像nicknamefirst_namelast_name等只選擇鍵一個新的數組最簡單的方法?

+0

@Martijn的問題是如何獲得這些鍵的值。 https://stackoverflow.com/questions/12887322/get-only-the-array-elements-with-certain-keys – tilz0R

+0

選定的鍵是固定的還是動態的? –

+0

他們是固定@KOUSIKMANDAL – Leff

回答

3

使用array_flip()array_intersect_key()

$new_array = array_intersect_key($your_array, /* main array*/ 
        array_flip(/* to be extracted */ 
         array('nickname', 'first_name','last_name') 
       ) 
); 
+1

謝謝你,那正是我正在尋找的! – Leff

+0

@Leff:不客氣 –

1

試試這個;

$newArray = array(); 
$newArray['nickname'] = $meta['nickname']; 
$newArray['first_name'] = $meta['first_name']; 
$newArray['last_name'] = $meta['last_name']; 

如果密鑰數量不是很多,這很有用。

如果鑰匙很多,那麼你可以去

$requiredKeys = ['nickname','first_name','last_name']; 
foreach ($arr as $key => $value) { 

     if(in_array($key,$requiredKeys)) 
       $newArray[$key] = $meta[$key]; 
} 
相關問題