You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter 4中数字转指定字母字符串的实现问题求助

问题:数字转指定字母替换结果不符合预期

需要从视图获取数字输入,拆分单个数字后替换为指定字母再存入数据库,但替换结果与预期不符。以下是代码、执行结果及预期目标:

代码实现

$data = [
            'product_id' => $productId,
            'vendor_id' => $vendor_id,
            'purchase_date' => $purchase_date,
            'landing_price' => $landing_price,
            'retail_price' => $retail_price,
            'wholesale_price' => $wholesale_price,
            'current_price' => $current_price,
            'vendor_current_price' => $vendor_current_price,
            'freight' => $freight
        ];

$numbers = str_split($wholesale_price);

$replaceNumbers = [
            1 => 'S',
            2 => 'H',
            3 => 'O',
            4 => 'N',
            5 => 'E',
            6 => 'L',
            7 => 'A',
            8 => 'P',
            9 => 'U',
            0 => 'R'
];
$replace = str_replace($numbers, $replaceNumbers, $numbers);

$JoinReplacedWord = join($replace);
var_dump($numbers, $replace, $JoinReplacedWord);
die;

执行结果

array(4) { 
    [0]=> string(1) "1" 
    [1]=> string(1) "4" 
    [2]=> string(1) "5" 
    [3]=> string(1) "0" 
} 
array(4) { 
    [0]=> string(1) "S" 
    [1]=> string(1) "H" 
    [2]=> string(1) "O" 
    [3]=> string(1) "N" 
} 
string(4) "SHON"

预期目标

将数字1、4、5、0分别替换为S、N、E、R,最终拼接成字符串SNER。


问题原因

str_replace的数组替换逻辑是按数组索引位置一一对应,而非按查找值匹配替换数组的键。你的代码中:

  • $numbers是待替换的字符串数组(["1","4","5","0"])
  • $replaceNumbers是键为整数的关联数组,其元素顺序为S、H、O、N、E、L、A、P、U、R(按键的定义顺序)

执行str_replace($numbers, $replaceNumbers, $numbers)时,会将$numbers的第n个元素替换为$replaceNumbers的第n个元素,而非根据数字值匹配对应键的替换值,因此得到了错误的SHON。


解决方案

直接遍历每个数字,根据其值匹配替换数组的对应键即可,有两种实现方式:

方式一:遍历转换

$replace = [];
foreach ($numbers as $num) {
    // 将字符串数字转为整数,匹配替换数组的键
    $replace[] = $replaceNumbers[(int)$num];
}

方式二:调整替换数组键为字符串,使用array_map

// 将替换数组的键改为字符串类型,与$numbers中的元素类型一致
$replaceNumbers = [
    "1" => 'S',
    "2" => 'H',
    "3" => 'O',
    "4" => 'N',
    "5" => 'E',
    "6" => 'L',
    "7" => 'A',
    "8" => 'P',
    "9" => 'U',
    "0" => 'R'
];

$replace = array_map(function($num) use ($replaceNumbers) {
    return $replaceNumbers[$num];
}, $numbers);

两种方式处理后,$replace都会得到["S","N","E","R"],拼接后即为预期的SNER。


内容的提问来源于stack exchange,提问作者shreerangam vinay kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 13:45:29