php数字转中文

function numToWord($num)
{
    $chiNum = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
    $chiUni = array('','十', '百', '千', '万', '亿', '十', '百', '千');

    $chiStr = '';

    $num_str = (string)$num;

    $count = strlen($num_str);
    $last_flag = true; //上一个 是否为0
    $zero_flag = true; //是否第一个
    $temp_num = null; //临时数字

    $chiStr = '';//拼接结果
    if ($count == 2) {//两位数 
        $temp_num = $num_str[0];
        $chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
//当以1开头 都是十一,十二,以十开头的 我们就取$chiUni[i]也就是十
当不是以1开头时,而是以2,3,4,我们取这个数字相应的中文并拼接上十
        $temp_num = $num_str[1];
        $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
//取得第二个值并的到他的中文
    }else if($count > 2){
        $index = 0;
        for ($i=$count-1; $i >= 0 ; $i--) {
            $temp_num = $num_str[$i];         //获取的个位数
            if ($temp_num == 0) {
                if (!$zero_flag && !$last_flag ) {
                    $chiStr = $chiNum[$temp_num]. $chiStr;
                    $last_flag = true;
                }
            }else{
                $chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
//$index%9 index原始值为0,所以开头为0 后面根据循环得到:0,1,2,3...(不知道为什么直接用$index而是选择$index%9  毕竟两者结果是一样的)
//当输入的值为:1003 ,防止输出一千零零三的错误情况,$last_flag就起到作用了当翻译倒数第二个值时,将$last_flag设定为true;翻译第三值时在if(!$zero&&!$last_flag)的判断中会将其拦截,从而跳过
                $zero_flag = false;
                $last_flag = false;
            }
            $index ++;
        }
    }else{
        $chiStr = $chiNum[$num_str[0]];    //单个数字的直接取中文
    }
    return $chiStr;
}
原文出处:http://www.jb51.net/article/69742.htm
注意:如果输入的数字为0123  会输出下面的中文;0并不会被删除掉
 

猜你喜欢

转载自blog.csdn.net/linyunping/article/details/79225026