如何實現php數字轉漢字?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
php數字轉漢字的實現方法:首先創建一個PHP代碼示例文件;然后定義一個“number2Chinese”方法;接著在方法體中通過switch循環語句實現轉換邏輯;最后執行該文件即可。
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 = '';
// 千位
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<$j; $i++) {
$t = (int)$fl[$i];
$chs.= $str[0][$t];
}
}
return $chs;
}關于如何實現php數字轉漢字問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。