使用PHP将数字更改为单词

时间:2014-01-05 00:59:32

标签: php

我在PHP中有一个等式给出一个数字。如何在将数字返回HTML之前将其转换为单词?

$progress = round($number);
1='Very Good';
2='Good';
3='Average';
4='Bad';
5='Very Bad';
return $progress;

4 个答案:

答案 0 :(得分:2)

使用关联数组

$progress = round($number);

$progress_text = array(
1 => 'Very Good',
2 => 'Good',
3 => 'Average',
4 => 'Bad',
5 => 'Very Bad'
);

echo isset($progress_text[$progress]) ? $progress_text[$progress] : 'Unknown';

答案 1 :(得分:1)

有很多方法可以做到。

一个是创建一个函数:

function wordify($number) {
    switch($number) {
        case 1:
            return 'Very Good';
            break;
        case 2:
            return 'Good';
            break;
        case 3:
            return 'Average';
            break;
        case 4:
            return 'Bad';
            break;
        case 5:
            return 'Very Bad';
            break;
        default:
            return 'error';
            break;
    }
}

然后调用它:

echo wordify(4); // outputs "Bad"

答案 2 :(得分:1)

将数字描述放在数组中,然后返回与数字对应的数组索引:

$progress = round($number);
$numbers = array(
    1 => 'Very Good',
    2 => 'Good',
    3 => 'Average',
    4 => 'Bad',
    5 => 'Very Bad',
);
if ( isset( $numbers[$progress] ) )
    return $numbers[$progress];
else
    return 'Unknown';

答案 3 :(得分:1)

试试这个:

<?php

    $choice  = 1;//example number = 1
    $choices = array(
        1 => 'Very Good',
        2 => 'Good',
        3 => 'Average',
        4 => 'Bad',
        5 => 'Very Bad'
    );

    if (isset($choices[round($choice)])) echo $choices[round($choice)];
    else echo "NONE";


?>