0

我在前端的 Wordpress 中使用了以下 php,以显示我的博客有多少总评论。所以说例如会渲染以显示这种效果:1,265,788

<?php
$comments_count = wp_count_comments();
echo number_format($comments_count->total_comments);
?>

我想做的是更好地格式化数字。因此,它不会说我有 1,265,788 条评论,而是说我有 1,265M 条评论。

我按照另一篇文章的推荐尝试了以下代码,但也不起作用。它回显了完整的数字。

<?php
$comments_count = wp_count_comments();
if ($comments_count->total_comments < 1000000) {
    // Anything less than a million
    $n_format = number_format($comments_count->total_comments);
    echo $n_format;
} else if ($comments_count->total_comments < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($comments_count->total_comments / 1000000, 3) . 'M';
    echo $n_format;
} else {
    // At least a billion
    $n_format = number_format($comments_count->total_comments / 1000000000, 3) . 'B';
    echo $n_format;
}
?>

所以不,这不是一个重复的问题。以前的答案对我绝对没有帮助。我完全按照答案所说的那样尝试,我得到的输出是原始顶部代码给我的完整数字。

任何人都知道我如何实现这一点,并可以给我看一个样本。

谢谢!

4

1 回答 1

1

实际上上面的代码工作正常,输出是1.266M

硬编码示例:

$number = 1265788;
if ($number < 1000000) {
    // Anything less than a million
    $n_format = number_format($number);
    echo $n_format;
} else if ($number < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($number / 1000000, 3) . 'M';
    echo $n_format;
} else {
    // At least a billion
    $n_format = number_format($number / 1000000000, 3) . 'B';
    echo $n_format;
}

动态的:

$comments_count = wp_count_comments();
$number = $comments_count->total_comments;
if ($number < 1000000) {
    // Anything less than a million
    $n_format = number_format($number);
    echo $n_format;
} else if ($number < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($number / 1000000, 3) . 'M';
    echo $n_format;
} else {
    // At least a billion
    $n_format = number_format($number / 1000000000, 3) . 'B';
    echo $n_format;
}
于 2013-07-07T19:51:45.410 回答