2015-11-02 56 views
0

尋找無處不在,但找不到解決方案。每個人都在談論一組像這樣:如何在php表單處理器中獲得多組複選框值?

<input type="checkbox" value="red" name="colors[]"> red<br /> 
<input type="checkbox" value="purple" name="colors[]"> purple<br> 
<input type="checkbox" value="blue" name="colors[]"> blue<br> 
<input type="checkbox" value="black" name="colors[]"> black<br> 

,但我需要做多個組在一個單一的形式是這樣的:

<input type="checkbox" value="red" name="colors[]"> red<br /> 
<input type="checkbox" value="purple" name="colors[]"> purple<br> 
<input type="checkbox" value="blue" name="colors[]"> blue<br> 
<input type="checkbox" value="black" name="colors[]"> black<br> 
<input type="checkbox" value="sm" name="sizes[]"> small<br /> 
<input type="checkbox" value="med" name="sizes[]"> medium<br> 
<input type="checkbox" value="lrg" name="sizes[]"> large<br> 
<input type="checkbox" value="xlrg" name="sizes[]"> x-large<br> 

,並在此之上的形式是動態的。名稱是可變的和未知的,所以在PHP後代碼中,它不能是$ _POST ['colors']。

我有這樣的片段,可以抓住所有未知的名字,並建立一個消息後插入到郵件腳本電子郵件提交的表單值:

foreach ($_POST as $field=>$value) { 
    if ($field != "submit") $msg .= $field . ": " . $value . "\n"; 
} 

但正如你可能知道,當它到達一組複選框,它表示值是「數組」,因此不僅需要將數組拆分或分解爲複選框的多個值,還需要爲多組複選框執行此操作。

因此,例如,這可能是味精是一種特定形式是什麼$:

first_name: first 
last_name: last 
email_address: [email protected] 
phone: 1234567890 
variable_radio_name: answer 
variable_selectbox_name: answer 
colors_from_checkbox_group_one: red,blue 
sizes_from_checkbox_group_two: med,lrg 
variable_textarea_name: blah blah blah 

文本框,文本域,收音機,下拉框都容易,因爲它是一個答案了一塊,但這些複選框是疼痛。

編輯

這樣做是這樣的:

if ($field != "submit") $msg .= $field . ": " . is_array($value) ? implode(',', $value) . "\n" ? $value . "\n"; 

像這樣:

if ($field != "submit") { 
    $msg .= $field . ": " . is_array($value) ? implode(',', $value) . "\n" ? $value . "\n"; 
} 

語法錯誤兩種方式。

+0

見編輯的問題。 – leoarce

回答

1

您的語法錯誤是使用?兩次而不是:作爲三元發送部分。另外,你需要括號正確使級聯工作:

$msg .= $field . " : " . (is_array($value) ? implode(',', $value) . "\n" : $value . "\n"); 

這可能是更具可讀性:

if ($field != "submit") { 
    if(is_array($value)) { 
     $msg[] = "$field : " . implode(',', $value); 
    } else { 
     $msg[] = "$field : $value"; 
    } 
} 
$msg = implode("\n", $msg); 
+0

抱歉。我受到了追蹤。是的,這很好。我很感激。 – leoarce