3

我的代码中有以下内容:

 $my_count = count($total_elements[$array_object]);

$my_count现在包含$total_elements[$array_object]. 我想把这个数字转换成它对应的自然数(零,一,二,...)

在这种特定情况下,我只有 5 个数字

$numbers  = array(
    2  => 'two',
    3  => 'three',
    4  => 'four',
    5  => 'five',
    6  => 'six',
);

如何检索给定数组中的元素数,然后echo从数组中检索相应的自然数(人类可读数)?或者更好 - 有没有更好的方法来做到这一点?

(我已经找到了一些函数来做到这一点 - 但现在这些对于我现在需要的简单案例来说太臃肿了)

现在,我当然可以这样做switch()

switch ($my_count) {
    case 0:
        echo "zero";
        break;
    case 1:
        echo "one";
        break;
    case 2:
        echo "two";
        break;
      // etc...
}

但它对我来说看起来并不优雅。如果一个数字超过 10 个,也很愚蠢。

我确信有一种更优雅的方法可以实现这一点,即使现在我只有 5 个数字,我也希望有一些功能可以在其他情况下重复使用。

(如果这是一个愚蠢的问题,我很抱歉 - 但是 - 在 SE 或 Google 上使用关键字搜索PHP-我只找到了wordscount()计算字符串中的单词相关的答案)

4

5 回答 5

6

梨有一个数字单词的包装。看看这个梨 Number_word

$numbers = new Number_Words();
echo $number->toWords(200);

它会帮助你

编辑

您可以在 php中使用NumberFormatter类。

$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);  
echo $f->format(200);

它将输出“两百”

于 2013-12-01T05:59:58.023 回答
5

如果您只需要检索 5 个数字,则当前方法很好。创建一个关联数组,其中包含作为键的数字和作为值的相应单词:

$numberArray  = array(
    0  => 'zero',
    1  => 'one',
    2  => 'two',
    3  => 'three',
    4  => 'four',
    5  => 'five',
    6  => 'six',
    // ...
);

现在,检索对应的单词$my_count

$my_count = 2;
echo $numberArray[$my_count]; // => two

您可以选择isset()在尝试使用之前检查索引是否已定义echo。这种方法适用于最多 10 的数字。但是,这显然不适用于更大的数字,因为它需要更复杂的规则。用 10 或 20 行代码创建一个函数并不容易。我建议您使用现有的解决方案,而不是尝试从头开始创建一个。看看Number_WordsPEAR 类

于 2013-12-01T05:49:50.207 回答
4

如果只是少数几个:

$number = count($yournameit);
$count_words = array( "zero", "one" , "two", "three", "four" );
echo $count_words[$number];
于 2013-12-01T05:52:19.840 回答
3

使用内置 php 函数没有快速简便的方法来实现这一点,但是您可以使用这个 pear 包来实现:http: //pear.php.net/package/Numbers_Words

于 2013-12-01T05:51:08.180 回答
2

PEAR Numbers_Words 包提供了在单词中拼写数字的方法。

参考:

梨: http: //pear.php.net/package/Numbers_Words

PECL: http: //php.net/manual/en/numberformatter.format.php

例子:

echo number_to_word( '2281941596' );

//Sample output - number_to_word
Two Billion, Two Hundreds Eighty One Million, Nine Hundreds Forty One Thousand and Five Hundreds Ninety Six

//Sample output - PEAR Class
 two billion two hundred eighty-one million nine hundred forty-one thousand five hundred ninety-six
于 2013-12-01T06:02:30.027 回答