复制手册中的示例,ngettext 的工作方式如下:
ngettext("%d window", "%d windows", 1); //'1 window';
ngettext("%d window", "%d windows", 2); //'2 windows';
但是如果我想使用 2 个变量,例如
%d windows %d doors
,该怎么办?是否有一个标准方法来实现这一点,以便根据 2 个变量出现正确的字符串(4 种组合)?
ngettext()
不支持多个变量。您必须确保编写的句子可以逐块正确翻译(如果可能的话,多个句子以避免与语言相关的排序问题)。
不支持这一点的至少一个原因是,必需的后备句子(
ngettext()
的第一个参数)的数量将随着变量的数量呈指数增长(即,对于2个变量,您需要4个这样的句子:单数-单数,单数-复数、复数-单数和复数-复数,然后 8 个变量,等等)。
您可以在https://stackoverflow.com/a/1893929/4457767找到类似问题的答案。
/**
* Function that will return the correct word related to quantity.
* @param type Int $quantity
* @param type String $singular
* @param type String $plural
* @param type Boolean $showQuantity
* @return type String
*/
function pluralize( $quantity, $singular, $plural, $showQuantity=true ) {
return ( $showQuantity ? $quantity." " : "" ) . ( $quantity > 1 ? $plural : $singular );
}