为了从县获得著名的运动,我创建了这个表格。
$sports = array (
'Australia' => array (
1 => 'Cricket',
2 => 'Foot Ball',
3 => 'Net Ball',
4 => 'Kabadi',
5 => 'Ragby',
6 => 'Basket Ball',
7 => 'Volley Ball',
),
'New Zealand' => array (
1 => 'Cricket',
2 => 'Foot Ball',
3 => 'Net Ball',
4 => 'Ragby',
5 => 'Basket Ball',
),
'England' => array (
1 => 'Cricket',
2 => 'Foot Ball',
3 => 'Net Ball',
4 => 'Ragby',
5 => 'Karom',
6 => 'Basket Ball',
7 => 'Table Tennis',
8 => 'Tennis',
),
);
echo '<br><form action="" method="post">';
foreach ( $sports AS $country => $sport ) {
echo "<h3>{$country}</h3\n";
foreach ($sport AS $k => $v) {
echo "<br /><input type='checkbox' name='country-sport[{$country}][]' value='{$k}' />{$v}\n";
}
}
echo "\n<br><input type='submit' value='go' />\n</form>";
我的问题是当我要验证这一点时。在这里,我需要使用此表单验证检查一些条件。
- country-subject 数组是否完全为空
- 每个国家/地区至少选择了 1 项或最多 3 项运动
不满足这些条件需要显示错误信息。
我尝试了这样的事情..使用此代码,我可以获得第一个错误消息,即如果整个数组为空..
更新:到目前为止,这是我的验证码..
if ( isset($_POST['country-sport']) && is_array( $_POST['country-sport'])) {
foreach ( $_POST['country-sport'] AS $country => $sport) {
if ( count($sport) >= 1 && count($sport) <= 3) { //checking that it has 3 or more values.
//process
} else {
echo "select at leat 1 or upto 3 sports for {$country} ";
}
}
} else {
echo 'You have not selected sports for any country!';
}
更新:使用 var_dump($_POST['country-sport']);
array(3) {
["Australia"]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
["New Zealand"]=>
array(3) {
[0]=>
string(1) "2"
[1]=>
string(1) "3"
[2]=>
string(1) "4"
}
["England"]=>
array(3) {
[0]=>
string(1) "6"
[1]=>
string(1) "7"
[2]=>
string(1) "8"
}
}