php - php导入excel文件报错函数str_replace
问题描述
我有下面的代码,目的是自动添加产品代码。例如,如果产品代码字段留空,则默认的第一个产品将为 SP00001。下一个产品将是 SP00002... 该代码在手动添加产品时仍然可以正常工作。但是,当我使用 excel 文件导入数据时,出现上述代码错误。产品代码运行的地方比较乱,只有第一个产品是代码SP00001,然后是完整的SP00002。下次输入代码时,代码重复了很多次,却不知道出了什么问题。谢谢你的帮助。
public function cms_save_product($data){
$store_id = $this->auth['store_id'];
$data['user_init'] = $this->auth['id'];
if ($data['prd_code'] == '') {
$code = $this->db
->select('prd_code')
->from('products')
->like('prd_code', 'SP')
->order_by('created desc')
->get()
->row_array();
if(empty($code)){
$data['prd_code'] = 'SP00001';
}else{
$max_code = (int)(str_replace('SP', '', $code['prd_code'])) + 1;
if ($max_code < 10)
$data['prd_code'] = 'SP0000' . ($max_code);
else if ($max_code < 100)
$data['prd_code'] = 'SP000' . ($max_code);
else if ($max_code < 1000)
$data['prd_code'] = 'SP00' . ($max_code);
else if ($max_code < 10000)
$data['prd_code'] = 'SP0' . ($max_code);
else if ($max_code < 100000)
$data['prd_code'] = 'SP' . ($max_code);
}
}
$this->db->insert('products', $data);
}
解决方案
在寻找最佳产品代码时,您似乎正在使用记录创建日期进行订购。如果您在从电子表格导入时在循环中插入许多记录,并使用类似datetime
的时间格式,这将导致您的例程重复生成相同的代码,直到下一秒滴答作响。你应该使用类似的东西:
SELECT MAX(prd_code) FROM products WHERE prd_code LIKE 'SP%'
供您查询。这将确保您始终递增最高产品代码。
您还有一个问题,即最多有 99999 个产品代码,这可能太低了。
对于产品代码格式,使用str_pad可以大大简化您的逻辑。
这将用 SP00001 完全替换空代码,并使用正确数量的零处理代码的格式,以匹配所需的长度。
$defaultCode = 'SP';
if (empty($code))
{
$data['prd_code'] = $defaultCode;
}
else
{
// Remove the SP prefix from the product code and cast to an int
$numCode = (int)(str_replace('SP', '', $code['prd_code']));
// Increment code
$numCode++;
/*
* Set the pad length to either the size of the default code, or the
* length of the stored product code plus 2 (for "SP" prefix), whichever is larger.
* This ensures that the codes always begin with SP even if they are longer than expected.
*/
$padLength = max(strlen($defaultCode), strlen($numCode) + 2);
// Format the product code using the default code as a left pad
$data['prd_code'] = str_pad($numCode, $padLength, $defaultCode, STR_PAD_LEFT);
}
推荐阅读
- python - 如何获得距地球上某个点的精确距离的纬度/经度列表?
- xcode10 - Xcode 10 构建阶段 Shell 脚本
- css - 在primeng按钮上堆叠的字体很棒
- php - 表单提交时的散列变量更改
- reactjs - 如果第一个在 reactjs 中失败,则取消后续的 fetch 请求
- javascript - 如何在数据格式类似于 {"1":Data1, "2":Data2} 时将 JSON 数据解码为 php
- node.js - Docker:来自服务器的空响应
- javascript - 从反应js中的对象数组中删除一个元素
- javascript - 如果输入值为字符串,则更改窗口位置
- c# - 增加tesseract的力量