PHP“年”数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2807394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:44:24  来源:igfitidea点击:

PHP 'Years' array

phparraysdate

提问by JM4

I am trying to create an array for years which i will use in the DOB year piece of a form I am building. Currently, I know there are two ways to handle the issue but I don't really care for either:

我正在尝试创建一个多年的数组,我将在我正在构建的表单的 DOB 年份中使用它。目前,我知道有两种方法可以处理这个问题,但我并不真正关心:

1) Range:

1) 范围:

I know I can create a year array using the following

我知道我可以使用以下方法创建年份数组

<?php 
     $year = range(1910,date("Y"));
     $_SESSION['years_arr'] = $year;
?>

the problem with Point 1 is two fold: a) my function call shows the first year as 'selected' instead of "Year" as I have as option="0", and b) I want the years reversed so 2010 is the first in the least and shown decreasing.

第 1 点的问题有两个方面:a)我的函数调用将第一年显示为“已选择”而不是“年份”,因为我有选项 =“0”,并且 b)我希望年份颠倒,所以 2010 年是第一个至少并显示减少。

My function call is:

我的函数调用是:

PHP

PHP

<?php
    function showOptionsDrop($array, $active, $echo=true){
        $string = '';

        foreach($array as $k => $v){
            $s = ($active == $k)? ' selected="selected"' : '';
            $string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";     
        }

        if($echo)   echo $string;
        else        return $string;
    }
?>

HTML

HTML

<table>
            <tr>
            <td>State:</td>
            <td><select name="F1State"><option value="0">Choose a year</option><?php showOptionsDrop($_SESSION['years_arr'], null, true); ?></select>
            </td>
            </tr>
</table>


2) Long Array

2) 长数组

I know i can physically create an array with years listed out but this takes up a lot of space and time if I ever want to go back and modify.

我知道我可以物理创建一个列出年份的数组,但是如果我想回去修改,这会占用大量的空间和时间。

ex: PHP

例如:PHP

$years = array('1900'=>"1900", '1901'=>"1901", '1902'=>"1902", '1903'=>"1903", '1904'=>"1904", '1905'=>"1905", '1906'=>"1906", '1907'=>"1907", '1908'=>"1908", '1909'=>"1909", '1910'=>"1910", '1911'=>"1911", '1912'=>"1912", '1913'=>"1913", '1914'=>"1914", '1915'=>"1915", '1916'=>"1916", '1917'=>"1917", '1918'=>"1918", '1919'=>"1919", '1920'=>"1920", '1921'=>"1921", '1922'=>"1922", '1923'=>"1923", '1924'=>"1924", '1925'=>"1925", '1926'=>"1926", '1927'=>"1927", '1928'=>"1928", '1929'=>"1929", '1930'=>"1930", '1931'=>"1931", '1932'=>"1932", '1933'=>"1933", '1934'=>"1934", '1935'=>"1935", '1936'=>"1936", '1937'=>"1937", '1938'=>"1938", '1939'=>"1939", '1940'=>"1940", '1941'=>"1941", '1942'=>"1942", '1943'=>"1943", '1944'=>"1944", '1945'=>"1945", '1946'=>"1946", '1947'=>"1947", '1948'=>"1948", '1949'=>"1949", '1950'=>"1950", '1951'=>"1951", '1952'=>"1952", '1953'=>"1953", '1954'=>"1954", '1955'=>"1955", '1956'=>"1956", '1957'=>"1957", '1958'=>"1958", '1959'=>"1959", '1960'=>"1960", '1961'=>"1961", '1962'=>"1962", '1963'=>"1963", '1964'=>"1964", '1965'=>"1965", '1966'=>"1966", '1967'=>"1967", '1968'=>"1968", '1969'=>"1969", '1970'=>"1970", '1971'=>"1971", '1972'=>"1972", '1973'=>"1973", '1974'=>"1974", '1975'=>"1975", '1976'=>"1976", '1977'=>"1977", '1978'=>"1978", '1979'=>"1979", '1980'=>"1980", '1981'=>"1981", '1982'=>"1982", '1983'=>"1983", '1984'=>"1984", '1985'=>"1985", '1986'=>"1986", '1987'=>"1987", '1988'=>"1988", '1989'=>"1989", '1990'=>"1990", '1991'=>"1991", '1992'=>"1992", '1993'=>"1993", '1994'=>"1994", '1995'=>"1995", '1996'=>"1996", '1997'=>"1997", '1998'=>"1998", '1999'=>"1999", '2000'=>"2000", '2001'=>"2001", '2002'=>"2002", '2003'=>"2003", '2004'=>"2004", '2005'=>"2005", '2006'=>"2006", '2007'=>"2007", '2008'=>"2008", '2009'=>"2009", '2010'=>"2010");

$_SESSION['years_arr'] = $years_arr;

Does anybody have a recommended idea how to work - or just how to simply modify my existing code?

有没有人有推荐的想法如何工作 - 或者只是如何简单地修改我现有的代码?

Thank you!

谢谢!

回答by Brenton Alker

Not sure why you're using the session for this, but generating the array can be done with the array_combinefunction.

不确定为什么要为此使用会话,但可以使用array_combine函数生成数组。

$years = array_combine(range(date("Y"), 1910), range(date("Y"), 1910));

Reversing the parameters to rangewill give you a descending array and array_combine will use the first array as the keys and the second as the values, giving the array(1910 => 1910, ...);map you're after.

将参数反转为range将为您提供一个降序数组,array_combine 将使用第一个数组作为键,第二个作为值,从而提供array(1910 => 1910, ...);您想要的地图。

回答by Anurag

reverse the numbers in the range to get years in descending order

反转范围内的数字以按降序获得年份

$years = range(2010, 1900); // => [2010, 2009, 2008, ... ]

use date('Y') instead of hard-coding the current year

使用 date('Y') 而不是硬编码当前年份

$years = range(date('Y'), 1900);

append an option "Select year" at the beginning

在开头附加一个选项“选择年份”

array_unshift($years, "Select year");

And finally why have a select drop-down for year or date of birth at all? It might be prevalent but it's super irritating. A simple text-box with validations, something like dd/mm/yyyyor mm/dd/yyyyis way better. Having drop-downs for date, month, and year only means that a user is allowed to select valid values and not necessarily correct values if they find it convoluted just to input a date. Moreover, since users can still enter junk values by modifying the DOM, validations need to be done on the server side. If validations are being done on the server-side, might as well just offer them a simple text box.

最后,为什么要为年份或出生日期选择下拉菜单?它可能很普遍,但它非常刺激。一个带有验证的简单文本框,类似于dd/mm/yyyymm/dd/yyyy更好。具有日期、月份和年份的下拉列表仅意味着允许用户选择有效值,如果他们发现仅输入日期就很复杂,则他们不一定选择正确的值。此外,由于用户仍然可以通过修改 DOM 来输入垃圾值,因此需要在服务器端进行验证。如果验证是在服务器端完成的,不妨为他们提供一个简单的文本框。

Also drop-downs make client-side coding complex. For example, if Feb and a leap year are selected, then a days dropdown should contain 29 days, otherwise 28.

下拉菜单也使客户端编码变得复杂。例如,如果选择了二月和闰年,则天数下拉列表应包含 29 天,否则为 28。

回答by allen.mak

Why do you need to store the array into the session?

为什么需要将数组存储到会话中?

Based on your use case, you do not need to use the array to store data beforehand.

根据您的用例,您不需要预先使用数组来存储数据。

define('DOB_YEAR_START', 1900);

$current_year = date('Y');

for ($count = $current_year; $count >= DOB_YEAR_START; $count--)
{
    print "<option value='{$count}'>{$count}</option>";
}

回答by Ben

Why don't you do this on your first approach

你为什么不在你的第一个方法中这样做

    foreach($array as $k){
        $string .= '<option value="'.$k.'">'.$k.'</option>'."\n";     
    }

Semantically, and functionally, speaking it's better to use the year as valuethan an int.

从语义上和功能上来说,使用年份value比使用int.

Also, use drawnonward method to get an inverted array so the year 2010 is the first, and default, value on your list.

此外,使用 drawonward 方法获取倒排数组,因此 2010 年是列表中的第一个默认值。

回答by Ben Rowe

I'd go with option #1. However all you need to do is prepend a value to the array before you print it:

我会选择#1。但是,您需要做的就是在打印之前为数组添加一个值:

<?php 
$years = $_SESSION['years_arr'];
// reverse the year list
rsort($years);
// prepend the 'choose a year' value to the array
array_unshift($years, 'Choose a year');
?>

<td><select name="F1State"><?php showOptionsDrop($years, null, true); ?></select>

回答by user3292639

you can simply use PHP foreach() function!

你可以简单地使用 PHP foreach() 函数!

example:

例子:

$years_now = date("Y");

echo '<select name="y">';   
echo '<option value="" disabled>Now:</option>';
            echo '<option value="'.$years_now.'" selected="selected">'.$years_now.'</option>';
            echo '<option value="" disabled>Other:</option>';               
            foreach (range($years_now, 1910) as $years) {       
                echo '<option value="'.$years.'">'.$years.'</option>';          
            }           
        echo '</select>';

回答by pfwd

Extending Brenton Alker's answer; if you need to add something to the start of the array you could do something like this:

扩展 Brenton Alker 的回答;如果您需要在数组的开头添加一些内容,您可以执行以下操作:

$keys =  array_merge(['any'], range(date("Y"), 1910));
$values = array_merge(['Any'], range(date("Y"), 1910));
$choice = array_combine($keys, $values);

This will add the key/value of any/Any to the start of the array whilst keeping all the subsequent keys in place

这会将 any/Any 的键/值添加到数组的开头,同时保留所有后续键

回答by drawnonward

In option 1 add:

在选项 1 中添加:

$year = array_reverse( $year );

or just use:

或者只是使用:

$year = range( date("Y") , 1910 );

回答by Tim

If just reversing the order of your year array is the goal you can use the array_reverse()function.

如果只是颠倒年份数组的顺序是您可以使用该array_reverse()函数的目标。

http://www.php.net/manual/en/function.array-reverse.php

http://www.php.net/manual/en/function.array-reverse.php

回答by ortuna

part 2:

第2部分:

$years = array();
for($i = 1900;$i<= 2010;$i++)
    $years["$i"] = $i;