首页 > 解决方案 > 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);
}

标签: php

解决方案


在寻找最佳产品代码时,您似乎正在使用记录创建日期进行订购。如果您在从电子表格导入时在循环中插入许多记录,并使用类似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);
}

推荐阅读