我有以下函数:
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return __('0 View','mm');
}
return $count. __(' Views','mm');
}
如何使其格式化数字以在千分之一位中包含逗号?例如,50000 应变为 50,000。
使用 number_format()
:
number_format($number);
您可以使用
number_format
.
看看number_format
.
例如:
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
$number=number_format($number);
您的数字格式使用是正确的,可以获得您正在寻找的漂亮格式。 我认为您在更改数据库中的格式时遇到的问题是您正在格式化数字并将其重新保存在自身上。
例如:
$count = 5000;
$count = number_format($count);
//$count is no longer equal to 5000, it is now a string 5,000
尝试使用临时变量,这样原始$count变量就不会更改,并且当您写回数据库时,它仍将采用所需的格式。
例如:
$count = 5000;
$tmpCount = 0;
$tmpCount = number_format($count);
// $count is still 5000, and $tmpCount now holds the value 5,000.
您代码的更新版本,我假设您只希望元包含逗号分隔值?
function setPostViews($postID) {
//Set initial variables
$count_key = 'post_views_count';
$tmpCount = 0;
$count = get_post_meta($postID, $count_key, true);
if($count == '') {
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
} else {
$count++;
//Set tmpCount variable to hold comma separated value
$tmpCount = number_format($count);
//Comma separated value is passed into your function
update_post_meta($postID, $count_key, $tmpCount);
}
}
这就是你所希望的吗? 或者,如果您只想在向用户显示时以这种方式格式化此数字,但数据库保持正确(不逗号分隔(,则在查询数据库后,保存 db 值并创建一个逗号分隔的变量,就像我上面所做的那样。 然后,在任何数据库函数上,引用 $count 变量,在任何用户输出函数上,使用 $tmpCount 变量。
再次,我希望这能回答你的问题,如果不是,请澄清。