我對 PHP 很陌生,只是一般的代碼,所以如果我的代碼看起來一團糟,我深表歉意。
I've created a multidimensional array and when certain checkboxes are selected and submitted through the form, I want only the selected arrays items show. 例如,約翰史密斯的資訊和影像只有他被選中。
這是我的多維陣列:
<?php
$characters = array (
'john' =>
array (
'first_name' => 'John',
'last_name' => 'Smith',
'age' => '40',
'image_url' => 'images/john.png',
),
'jane' =>
array (
'first_name' => 'Jane',
'last_name' => 'Doe',
'age' => '30',
'image_url' => 'images/jane.png',
),
'sara' =>
array (
'first_name' => 'Sara',
'last_name' => 'Johnson',
'age' => '10',
'image_url' => 'images/sara.png',
)
)
?>
這是我的 html 表單:
<h3 class="form__heading"> Select characters to show </h3>
<form method="post">
<ul class="form__items">
<!--John-->
<li class="form__item">
<label for="john">John Smith </label>
<input id="john" type="checkbox" name="john">
</li>
<!--Jane-->
<li class="form__item">
<label for="jane">Jane Doe </label>
<input id="jane" type="checkbox" name="jane">
</li>
<!--Sara-->
<li class="form__item">
<label for="sara">Sara Johnson </label>
<input id="sara" type="checkbox" name="sara">
</li>
</ul>
<!--Button-->
<input class="form__button" type="submit" value="Show Characters">
</form>
我嘗試過 foreach 和 for 回圈,但我認為我只是做錯了。任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
我解決了你的問題,請查看我在下面給你的腳本
html代碼會是這樣的
<form action="index.php" method="post">
<ul class="form_items">
<!--John-->
<li class="form_item">
<label for="john">John Smith </label>
<input id="john" type="checkbox" name="characters[]" value="john">
</li>
<!--Jane-->
<li class="form__item">
<label for="jane">Jane Doe </label>
<input id="jane" type="checkbox" name="characters[]" value="jane">
</li>
<!--Sara-->
<li class="form_item">
<label for="sara">Sara Johnson </label>
<input id="sara" type="checkbox" name="characters[]" value="sara">
</li>
</ul>
和 php 腳本將是這樣的
<?php
$characters = array (
'john' =>
array (
'first_name' => 'John',
'last_name' => 'Smith',
'age' => '40',
'image_url' => 'images/john.png',
),
'jane' =>
array (
'first_name' => 'Jane',
'last_name' => 'Doe',
'age' => '30',
'image_url' => 'images/jane.png',
),
'sara' =>
array (
'first_name' => 'Sara',
'last_name' => 'Johnson',
'age' => '10',
'image_url' => 'images/sara.png',
)
);
if(isset($_POST['submit'])){
$selectedCharacter = $_POST['characters'];
foreach ($selectedCharacter as $Character) {
echo "first_name:- ".$characters[$Character]['first_name'].'<br>';
echo "last_name:- ".$characters[$Character]['last_name'].'<br>';
echo "age:- ".$characters[$Character]['age'].'<br>';
echo "image_url:- ".$characters[$Character]['image_url'].'<br><br>';
}
}
?>
請參閱此頻道https://www.youtube.com/channel/UCnqWFcMpFA_dsxEzt7lKxJA
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/378908.html
