2015-11-14 75 views
0

也許我的問題的類型不太清楚,但我不知道解釋我需要的更好方法。這裏是我在WordPress的一些自定義頁面上工作的東西,我有一個數組中的輸入字段。該數組中的輸入字段與第二個數組的id匹配,但實際上我需要獲得與第一個數組的id相匹配的第二個數組的類型字段。通過將第二個數組的密鑰ID與第一個數組的密鑰ID進行匹配來查找第二個數組的密鑰類型

這裏是第一陣列的示例

$first_array = array(
    'sample_text' => 'some text here', 
    'sample_textarea' => 'some text here in textarea field', 
    'sample_upload' => 'http://somelink.com/someimage.jpg' 
); 

這裏是第二陣列。

$second_array = array(
    array(
    'type' => 'upload', 
    'id' => 'sample_upload', 
    'title' => 'Sample upload button' 
    ), 

    array(
     'type' => 'textfield', 
     'id' => 'sample_text', 
     'title' => 'Sample text field' 
    ), 

    array(
     'type' => 'textarea', 
     'id' => 'sample_textarea', 
     'title' => 'Sample textarea field' 
    ), 
); 

所以基本上在第二陣列中首先用於產生在前端的輸入字段,但在形式提交表單提交的陣列,其看起來像第一示例中,所以現在第一陣列上我需要循環爲每個輸入和匹配第二個和第一個數組的id,但是當id匹配時,我需要輸入類型字段並應用該類型字段名稱的篩選器。

所以基本上

// loop through inputs in the array 
foreach($first_array as $key => $value) { 

    // Now the first $key would be 'sample_text' 

    // How to search $second_array for 'id' with 'sample_text' 

    // And if that 'id' exists, take the 'type' field and apply filter named same as that 'type' field 

} 

但我不知道究竟我怎麼會通過第二陣列和環獲得基於「身份證」「型」

+0

所以,你想第一個是第二個的索引? – weirdpanda

+0

如果這可行,我不知道,我已閱讀php.net,它看起來像這不是我想要的 –

回答

1

下面我想補充有益的鑰匙,第二陣列,像這樣:

$second_array = array(
    'sample_upload' => array(
    'type' => 'upload', 
    'id' => 'sample_upload', 
    'title' => 'Sample upload button' 
    ), 
    'sample_text' => array(
     'type' => 'textfield', 
     'id' => 'sample_text', 
     'title' => 'Sample text field' 
    ), 
    'sample_textarea' => array(
     'type' => 'textarea', 
     'id' => 'sample_textarea', 
     'title' => 'Sample textarea field' 
    ), 
); 

當循環訪問第一個數組時,可以使用已知鍵訪問第二個數組。

foreach ($first_array as $key => $value) { 
    $sa = $second_array[$key]; 
} 

即循環將通常具有在那裏一些更多的錯誤檢查碼,例如以確保密鑰存在,爲簡潔起見,這些密鑰已被省略。

+0

這實際上是非常有用的想法,但我想知道它會如何影響剩下的代碼,我使用這個數組,通過邏輯它不應該影響,因爲這基本上只是命名數組中的一個鍵。我今天測試了這個,看看它是否可以工作。如果它運作非常簡單的解決方案。 –

0

編輯:array_filter()不會爲原創作品雖然如此,你可以使用,而不是

function checkKey($item, $k, $key) { 
    return $item['id'] === $key; 
} 

foreach($first_array as $key => $value) { 
    // Now the first $key would be 'sample_text' 
    // How to search $second_array for 'id' with 'sample_text' 
    $sa = $second_array[array_walk($second_array, 'checkKey', $key)]; 
    // And if that 'id' exists, take the 'type' field and apply filter named same as that 'type' field 
} 
+0

看來,這不起作用,或者我不明白。 –

相關問題