书写技术成长之路

array_combine 函数的误区

情景是这样的,需要记录用户的身份证和姓名信息,前端以表单的方式提交过来

前端提交的数据格式

$id_cards[] = '3306821978072033829';
$id_cards[] = '371581199202123681';

$names[] = '小李';
$names[] = '小王';

后端接收到的数据是这样处理的

$names = ['小李', '小王'];
$id_cards = ['3306821978072033829', '371581199202123681'];

$inputs = array_combine($id_cards, $names);

foreach ($inputs as $key => $value) {
        $info['id_card'] = $key;
        $info['name'] = $value;
        $result[] = $info;
}

json_encode($result);

发现最后输出结果是这样的

{
    "id_card": 3306821978072033100,
    "name": "小李"
},
{
    "id_card": 371581199202123100,
    "name": "小王"
}

怎么后面变成100了呢?不细心看还真发觉不出来这个bug。 通过调试发现,数组$id_cards全是数字,PHP就把它当成整型来处理,这时候array_combine是用身份证号作为数组的键,然后本来以为$id_cards 中的元素是字符串,在用array_combine的时候就被隐式转换为整型了,这就可能会发生超出INT的最大值而导致意想不到的结果。

最后的解决方案就是为$id_cards的每个元素添加个字符串前缀, 然后再用array_combine

array_walk($id_cards, function(&$val) {
    $val = "E".$val;
    return $val;
});