[英]Plural and Singular terms in PHP
I am doing an amount of users check for our website, below is the code. 我正在做一些用户检查我们的网站,下面是代码。 How can i use the word "user" if there is only 1 account and how can i use "users" if there is >1.
如果只有一个帐户,我如何使用“用户”一词,如果> 1,我如何使用“用户”。
code: 码:
$result = mysql_query("SELECT * FROM users WHERE user_id='$userid'");
$num_rows = mysql_num_rows($result);
echo "amount of users.";
All of these answers will work well, but if you're looking for a reusable way, you can always externalise it: 所有这些答案都能很好地解决,但如果您正在寻找可重用的方法,您可以随时将其外部化:
function get_plural($value, $singular, $plural){
if($value == 1){
return $singular;
} else {
return $plural;
}
}
$value = 0;
echo get_plural($value, 'user', 'users');
$value = 3;
echo get_plural($value, 'user', 'users');
$value = 1;
echo get_plural($value, 'user', 'users');
// And with other words
$value = 5;
echo get_plural($value, 'foot', 'feet');
$value = 1;
echo get_plural($value, 'car', 'cars');
Or, if you want it to be even more automated, you can set it up to only need the $plural
variable set when it is an alternate word (eg: foot/feet): 或者,如果您希望它更加自动化,您可以将其设置为只需要
$plural
变量集,当它是替代单词时(例如:英尺/英尺):
function get_plural($value, $singular, $plural = NULL){
if($value == 1){
return $singular;
} else {
if(!isset($plural)){
$plural = $singular.'s';
}
return $plural;
}
}
echo get_plural(4, 'car'); // Outputs 'cars'
echo get_plural(4, 'foot'); // Outputs 'foots'
echo get_plural(4, 'foot', 'feet'); // Outputs 'feet'
也许我弄错了,但很明显:
echo $num_rows > 1 ? 'users' : 'user';
Try 尝试
if($num_rows === 1)
{
echo "user";
}
else
{
echo "users";
}
or in short form 或者简短形式
echo $num_rows === 1 ? "user" : "users";
if ($num_rows === 1) {
echo "a user.";
}
else if ($num_rows > 1) {
echo "amount of users.";
}
else {
echo "no users".
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.