【问题标题】:Simplify retrieving the option values for an html dropdown into a php array简化将 html 下拉列表的选项值检索到 php 数组中
【发布时间】:2015-03-31 05:55:09
【问题描述】:

我正在尝试获取下拉 html 菜单的选项并将这些选项放入 php 数组中。

下拉列表包含数值,表示文本短语的前 3 个偏好,将包含在电子邮件中。

我有一个可行的模型,但代码似乎有点笨拙,我想知道是否有更简单的方法来做到这一点?

我首先在 html 中创建下拉列表:

<div class="first_class">
  <div class="left_col">
    <p>
      <select name="choice_2">
        <option value="0" selected>_</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
    </p>
  </div>

然后我从 $_POST 中获取下拉值并将它们放入一个数组中

$choices = array('choice_2' => $_POST['choice_2']);

然后我使用 switch 语句将 $choices 数组值与文本短语相关联:

foreach ($choices as $key => $users_choice) {
  if ($users_choice > 0) {
    switch ($key) {
      case "choice_2":
        $choices_text[$choices_index++] = "This is the phrase the user selected as his choice"
        break;
}

现在 $choices_text 是一个包含用户选择文本的新数组。

它有效,但这似乎是一种将下拉菜单中的选项转换为文本短语的非常迂回的方法。

我是不是错过了什么。提前感谢您的帮助。

【问题讨论】:

  • 你真的相信foreach ($choices as $key =&gt; $users_choice)有什么意义吗?并且可以执行超过 1 次?你的问题不清楚。 $choices_index++ undefined an 没有意义。抱歉,但@MikeMiller 的回答更有意义。但是你写了It works, but this seems like a really roundabout way 我不明白它是如何工作的。但它总是设置 $choices_text[$choices_index++] = "This is the phrase the user selected as his choice" 独立于发布的用户选择

标签: php html arrays forms


【解决方案1】:

是的,有点笨重。您实际上不需要重新分配 post 数组或使用开关。仅使用 post 值来索引选项数组中的文本怎么样?例如

$text_you_want=$choices_text[$_POST['choice_2']];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2016-09-13
    相关资源
    最近更新 更多