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);
}

最新更新