如何对 PHP 中带编号的复选框表单中的值进行排名(优先排序)

How to rank (prioritize) values from numbered checkbox form in PHP

我正在使用下面的代码要求用户对他们更熟悉的编程语言进行排名。 用户需要从 1-3 排名(1 是他们最满意的)

<form id="form1" name="form1" method="post" action="">
<input type="number" name="php" required="required" max="3" min="1"/>PHP     <br />
<input type="number" name="python" required="required" max="3" min="1"/>Python <br />
<input type="number" name="ruby" required="required" max="3" min="1"/>Ruby <br /><br />
<input type="submit" name="button" id="button" value="Submit" />
</form>

一旦用户确定了编程语言的优先级并点击提交,我如何才能在下一页回应排名选择? (例如,您的第一选择是 x,第二选择是 y,第三选择是 z)

我不确定标签输入类型="number"是否存在。

你做得更好

<legend>
<label><input type="radio" name="php" value="1">1</label>
<label><input type="radio" name="php" value="2">2</label>
<label><input type="radio" name="php" value="3">3</label>
</legend>

 <legend>
<label><input type="radio" name="python" value="1">1</label>
<label><input type="radio" name="python" value="2">2</label>
<label><input type="radio" name="python" value="3">3</label>
</legend>

您不得将 'required' 属性用于单选标记或复选框标记

所以你检查javascript函数是否选中单选框。

<form name..... onsubmit = "return check_submit();">
<script>
var check_submit = function(){
  if($("input[name=php]:checked").val() =="")
  return false;
...
 return true;
}
</script>

或者您可以使用

<input type="text" name="php">

然后在下一页你可以这样做

$php = intval(trim($_POST['php']));
$python = intval(trim($_POST['python']));

$msg = "your first choice for php is '.$php;
$msg.="your second choice for phthon is '.$python;

.....etc..

我会这样做(请注意,我已经更改了表单元素上名称属性的值):

<form id="form1" name="form1" method="post" action="">
<input type="number" name="lang[php]" required="required" max="3" min="1"/>PHP     <br />
<input type="number" name="lang[python]" required="required" max="3" min="1"/>Python <br />
<input type="number" name="lang[ruby]" required="required" max="3" min="1"/>Ruby <br /><br />
<input type="submit" name="button" id="button" value="Submit" />
</form>

并且在 php 中:

//Get the form results (which has been converted to an associative array) from the $_POST super global
$langs = $_POST['lang'];

//Sort the values by rank and keep the key associations.
asort($langs, SORT_NUMERIC );

//Loop over the array in rank order to print out the values.
foreach($langs as $lang => $rank)
{
   //echo out here first, second, and third rank with each iteration respectively.
}

asort 函数只是按值对数组进行排序,同时保持键关联。