如何比较从下拉框中选择的值与数组元素?

时间:2011-08-24 20:25:11

标签: php mysql

我有一个包含2个数组的php文件

//script containing all the rublics and subrublics

$rublic[0]='rublic1';
$rublic[1]='rublic2';
$rublic[2]='rublic3';
$rublic[3]='rublic4';
$rublic[4]='rublic5';

$subrublic[0]='subrublic1';
$subrublic[1]='subrublic2';
$subrublic[2]='subrublic3';
$subrublic[3]='subrublic4';
$subrublic[4]='subrublic5';

?>

这些数组的元素显示在下拉框中。我需要做的是从框中抓取用户选择的元素,并将所选内容的索引号写入数据库字段。我怎么能这样做?

我会在这里发布我的代码,即使我意识到我从一开始就解决这个问题的方法是完全错误的:(

        //add the index number of the rublic and the subrublic to the db
    include('rublics.php');
    if(isset($_POST[' article_type']) && ($_POST['article_type'] != '0')){
        $rublic_selected = $_POST['article_type'];
        for($count_rublic=0;  $count_rublic<=10;  $count_rublic++){
            if($rublic_selected == $rublic[$count_rublic]) {
                $rublic_selected = $count_rublic;
            }
            if($rublic_selected == $subrublic[$count_rublic]){
                $rublic_selected = $count_rublic;
            }
        }
    } else {
        echo 'You did not make the selection. Please choose the type of the article.';
    }

2 个答案:

答案 0 :(得分:1)

您的下拉列表可以/应该使用value元素上option属性的索引号。即:

<select id="article_type" name="article_type">
<option value="0">rublic1</option>
<option value="1">rublic2</option>
<option value="2">rublic3</option>
<option value="3">rublic4</option>
<option value="4">rublic5</option>
</select>

然后当表单发布到您的PHP脚本时,您将已经有正确的索引号写入数据库。

答案 1 :(得分:0)

试试这个,这应该是一个好的开始:

$rublic[0]='rublic1';
$rublic[1]='rublic2';
$rublic[2]='rublic3';
$rublic[3]='rublic4';
$rublic[4]='rublic5';

$subrublic[0]='subrublic1';
$subrublic[1]='subrublic2';
$subrublic[2]='subrublic3';
$subrublic[3]='subrublic4';
$subrublic[4]='subrublic5';

//$user_input = 'rublic3';
$user_input = 'subrublic4';

$options = array('rublic', 'subrublic');
foreach($options as $option_key => $option_value)
{
    foreach($$option_value as $key => $value)
    {
        if($value == $user_input)
        {
            echo 'found it at ', $option_value, ' ', $key;
            break;
        }
    }
}

基本上,我遍历两个数组,直到找到匹配正确用户输入的字符串,并返回在(rublic或subrublic)中找到的数组的名称加上该数组的索引。