我制作了一个不依赖于 PHP 的 date(); 函数的函数,因为它不是必需的,但也使它尽可能紧凑和短。
代码:(共 121 字节)
function ordinal($i) { // PHP 5.2 and later
return($i.(($j=abs($i)%100)>10&&$j<14?'th':(($j%=10)>0&&$j<4?['st', 'nd', 'rd'][$j-1]:'th')));
}
下面是更紧凑的代码。
工作原理如下:
printf("The %s hour.\n", ordinal(0)); // The 0th hour.
printf("The %s ossicle.\n", ordinal(1)); // The 1st ossicle.
printf("The %s cat.\n", ordinal(12)); // The 12th cat.
printf("The %s item.\n", ordinal(-23)); // The -23rd item.
有关此功能的知识:
- 它处理负整数与正整数一样,并保留符号。
- 它按预期返回 -teen 数字的第 11、12、13、811、812、813 等。
- 它不检查小数,但会保留它们(在最终返回语句的开头使用
floor($i)、round($i) 或 ceil($i))。
- 您还可以在最后的 return 语句的开头添加
format_number($i) 以获得逗号分隔的整数(如果您要显示数千、数百万等)。
- 如果您只想在不输入任何内容的情况下返回序数后缀,则只需从 return 语句的开头删除
$i。
这个函数从 2006 年 11 月发布的 PHP 5.2 开始工作,纯粹是因为短数组语法。如果您有此之前的版本,请升级,因为您已经过时了将近十年!如果做不到这一点,只需将内联的['st', 'nd', 'rd'] 替换为包含array('st', 'nd', 'rd'); 的临时变量。
相同的函数(不返回输入),但为了更好地理解我的简短函数的分解图:
function ordinal($i) {
$j = abs($i); // make negatives into positives
$j = $j%100; // modulo 100; deal only with ones and tens; 0 through 99
if($j>10 && $j<14) // if $j is over 10, but below 14 (so we deal with 11 to 13)
return('th'); // always return 'th' for 11th, 13th, 62912th, etc.
$j = $j%10; // modulo 10; deal only with ones; 0 through 9
if($j==1) // 1st, 21st, 31st, 971st
return('st');
if($j==2) // 2nd, 22nd, 32nd, 582nd
return('nd'); //
if($j==3) // 3rd, 23rd, 33rd, 253rd
return('rd');
return('th'); // everything else will suffixed with 'th' including 0th
}
代码更新:
这是一个修改后的版本,它缩短了 14 个完整字节(总共 107 个字节):
function ordinal($i) {
return $i.(($j=abs($i)%100)>10&&$j<14?'th':@['th','st','nd','rd'][$j%10]?:'th');
}
或者尽可能短 25 个字节(总共 96 个字节):
function o($i){return $i.(($j=abs($i)%100)>10&&$j<14?'th':@['th','st','nd','rd'][$j%10]?:'th');}
使用最后一个函数,只需调用o(121);,它的作用与我列出的其他函数完全相同。
代码更新 #2:
Ben 和我一起工作并将其减少了 38 个字节(总共 83 个字节):
function o($i){return$i.@(($j=abs($i)%100)>10&&$j<14?th:[th,st,nd,rd][$j%10]?:th);}
我们认为它不可能比这更短!然而,愿意被证明是错误的。 :)
希望大家喜欢。