2017-02-27 107 views
0

如何從多維數組中禁用密鑰並獲取下一個出現密鑰。從數組搜索中禁用密鑰並獲取下一個密鑰

$array_example = array(

    'default_group' => 'styling', 

    'general' => esc_html__('General', THEMETEXTDOMAIN), 

    // User can enter it here 
    // 'default_group' => 'styling', 

    'styling' => esc_html__('Styling', THEMETEXTDOMAIN), 

    // 'default_group' => 'styling', 

    'animate' => esc_html__('Animate', THEMETEXTDOMAIN), 
) 

[default_group]鍵是一個固定鍵,但它可能在任何位置。

如果[default_group]鍵不存在或者它有一個空值,我需要獲取下一個鍵。

if(array_key_exists('default_group', $array_example) && !empty($array_example['default_group'])) { 

    $col_group_default = sanitize_text_field($array_example['default_group']); 

} else { 

    // Here I want to get the key BUT NOT [default_group]         

} 
+0

如果不使用數組以後,爲什麼不直接取消設置'()'它它分配給'$ col_group_default'後? – Darren

+0

我需要在此之後的完整陣列 –

+0

在'else {...'你循環陣列以獲得其他密鑰? – Darren

回答

0
$choice = ''; 
$default = array_search('default_group', array_keys($array_example)); 

if ($default && !empty($array_example[ $default ])) { 
    $choice = $array_example[ $default ]; 
} else { 
    $choice = isset($array_example[ $default + 1]) ? $array_example[ $default + 1] : $array_example[0]; 
} 
+3

歡迎來到stackov ....哦,等等,你在這裏足夠長的時間知道「這裏是codez」答案不是非常有幫助。請嘗試解釋如何以及爲什麼您發佈的代碼解決了OP問題。 –

+0

擴展的代碼還包含'$ default'爲空的最後一個元素,這會導致'$ default + 1'無效。 – RST

+0

@LJᛃ我認爲你錯了。我正在使用Op正在使用的確切邏輯,只是不同的功能。函數具有相當多的自定義名稱。你所描述的將是正確的,如果我只是拋出一些代碼在這個主題,http://stackoverflow.com/questions/42529018/combing-value-of-same-elements,我不知道。 – RST