首頁  >  文章  >  後端開發  >  php如何實現數位轉漢字

php如何實現數位轉漢字

藏色散人
藏色散人原創
2020-07-29 10:32:503091瀏覽

php數字轉漢字的實作方法:先建立一個PHP程式碼範例檔;然後定義一個「number2Chinese」方法;接著在方法體中透過switch循環語句實現轉換邏輯;最後執行該檔即可。

php如何實現數位轉漢字

推薦:《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<$len; $i+=4 ) {
        $s = array(0=>$str[$i], 1=>$str[$i+1], 2=>$str[$i+2], 3=>$str[$i+3]);
        $j = &#39;&#39;;
        // 千位
        if ($s[3] !== &#39;&#39;) {
            $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] !== &#39;&#39;) {
            $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] !== &#39;&#39;) {
            $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] !== &#39;&#39;) {
            $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(&#39;&#39;, $chinese);
    if ($fl) {
        $chs .= &#39;点&#39;;
        for($i=0,$j=strlen($fl); $i<$j; $i++) {
            $t = (int)$fl[$i];
            $chs.= $str[0][$t];
        }
    }
    return $chs;
}

以上是php如何實現數位轉漢字的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn