简体   繁体   English

如何使用for循环按降序排列值

[英]How to use for-loop for values in descending order

I am showing a list of years in a dropdown box. 我在下拉框中显示年份列表。 The years range from 2017 to the current year. 年份从2017年到当前年份。 Currently, the values are shown in my dropdown starting from 2017 and increasing up to the current year. 目前,这些值显示在我从2017年开始的下拉列表中,一直到当前年份为止。 But I want the values to be shown in descending order, with the current year (2019) on top, then 2018, and finally 2017. 但是我希望这些值以降序显示,当前年份(2019)在顶部,然后是2018,最后是2017。

Here is my current code: 这是我当前的代码:

<?php
for ($i=2017; $i < date("Y")+1; $i++) { 
?>
  <option value="<?php echo$i?>" <?php if($_POST['master_year']== $i) {echo 'selected';} ?>><?= $i;?></option>
<?php 
}
?>

How can I change this to show them in descending order? 我该如何更改以降序显示它们?

Simply change the order of your for loop. 只需更改for循环的顺序即可。 You initialize $i at 2017 to start. 您在2017年初始化$ i开始。 Then, you end it when it is equal to date("Y"). 然后,当它等于date(“ Y”)时结束它。 You add 1 to it each loop. 您在每个循环中添加1。 Reverse all of that: 颠倒所有这些:

for($i = date('Y'); $i >= 2017; $i--)

This is not unique to PHP. 这不是PHP独有的。 This is the basic construct of a for loop. 这是for循环的基本构造。 If you are having trouble with it, PLEASE do not develop anything critical. 如果您遇到麻烦,请不要开发任何关键的东西。 Take time to learn the basics of control structures in programming first. 首先花时间学习编程中的控制结构基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM