dopgv00024 2015-08-06 06:12
浏览 96
已采纳

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

I am using the code below to ask users to rank which programming language they are more comfortable with. The users need to rank from 1-3 (1 being the one they are most comfortable with)

<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>

Once the user prioritizes the programming languages and hits submit, how can I on the next page echo the ranking selection? (e.g. Your first choice is x, your second choice is y and your third choice is z)

  • 写回答

2条回答 默认 最新

  • drudfe0446838 2015-08-06 06:34
    关注

    I would do it like so (Note that I've changed the the value of the name attributes on the form elements):

    <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>
    

    And in the 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.
    }
    

    The asort function simply sorts the array by value while maintaining key association.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部