問題:
您有一個表單,它會產生多個輸入欄位,其中數組為他們的姓名(例如姓名[]和電子郵件[])。當您在 PHP 中檢索這些輸入時,您最終會得到一個連接的字串而不是單一陣列。如何將這些輸入轉換為正確的陣列?
解決方案:
將表單輸入陣列轉換為 PHP 中的單獨陣列:
實作:
$name = $_POST['name']; $email = $_POST['account']; foreach ($name as $key => $n) { // Get the corresponding email address using the key $e = $email[$key]; // Print the values or process them as needed echo "The name is $n and email is $e, thank you\n"; }
範例:
考慮以下形式:
例如:<input type="text" name="name[]" /> <input type="text" name="email[]" /> <input type="text" name="name[]" /> <input type="text" name="email[]" /> <input type="text" name="name[]" /> <input type="text" name="email[]" />考慮以下形式:
$_POST = [ 'name' => ['name1', 'name2', 'name3'], 'email' => ['email1', 'email2', 'email3'], ];
當您提交此表格時, $_POST陣列將包含以下內容:
foreach ($_POST['name'] as $key => $n) { $e = $_POST['email'][$key]; echo "The name is $n and email is $e, thank you\n"; }使用上述解決方案,您可以輕鬆存取和處理表單輸入:
The name is name1 and email is email1, thank you The name is name2 and email is email2, thank you The name is name3 and email is email3, thank you輸出:
以上是如何在 PHP 中正確存取和處理表單輸入數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!