AI编程助手
AI免费问答

php如何实现数字转汉字

藏色散人   2020-07-29 10:32   3348浏览 原创
php数字转汉字的实现方法:首先创建一个PHP代码示例文件;然后定义一个“number2Chinese”方法;接着在方法体中通过switch循环语句实现转换逻辑;最后执行该文件即可。

推荐:《PHP教程

PHP- 数字转汉字

//数字转汉字
function number2Chinese($num, $m = 1)
{
    switch($m) {
        case 0:
            $CNum = array(
                    array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖'),
                    array('','拾','佰','仟'),
                    array('','萬','億','萬億')
            );
            break;
        default:
            $CNum = array(
                    array('零','一','二','三','四','五','六','七','八','九'),
                    array('','十','百','千'),
                    array('','万','亿','万亿')
            );
            break;
    }
    // $cNum = array('零','一','二','三','四','五','六','七','八','九');
 
    if (is_integer($num)) {
        $int = (string)$num;
    } else if (is_numeric($num)) {
        $num = explode('.', (string)floatval($num));
        $int = $num[0];
        $fl  = isset($num[1]) ? $num[1] : FALSE;
    }
    // 长度
    $len = strlen($int);
    // 中文
    $chinese = array();
 
    // 反转的数字
    $str = strrev($int);
    for($i = 0; $i$str[$i], 1=>$str[$i+1], 2=>$str[$i+2], 3=>$str[$i+3]);
        $j = '';
        // 千位
        if ($s[3] !== '') {
            $s[3] = (int) $s[3];
            if ($s[3] !== 0) {
                $j .= $CNum[0][$s[3]].$CNum[1][3];
            } else {
                if ($s[2] != 0 || $s[1] != 0 || $s[0]!=0) {
                    $j .= $CNum[0][0];
                }
            }
        }
        // 百位
        if ($s[2] !== '') {
            $s[2] = (int) $s[2];
            if ($s[2] !== 0) {
                $j .= $CNum[0][$s[2]].$CNum[1][2];
            } else {
                if ($s[3]!=0 && ($s[1] != 0 || $s[0]!=0) ) {
                    $j .= $CNum[0][0];
                }
            }
        }
        // 十位
        if ($s[1] !== '') {
            $s[1] = (int) $s[1];
            if ($s[1] !== 0) {
                $j .= $CNum[0][$s[1]].$CNum[1][1];
            } else {
                if ($s[0]!=0 && $s[2] != 0) {
                    $j .= $CNum[0][$s[1]];
                }
            }
        }
        // 个位
        if ($s[0] !== '') {
            $s[0] = (int) $s[0];
            if ($s[0] !== 0) {
                $j .= $CNum[0][$s[0]].$CNum[1][0];
            } else {
                // $j .= $CNum[0][0];
            }
        }
        $j.=$CNum[2][$i/4];
        array_unshift($chinese, $j);
    }
    $chs = implode('', $chinese);
    if ($fl) {
        $chs .= '点';
        for($i=0,$j=strlen($fl); $i

php免费学习视频:立即学习
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。