Codeigniter生成循环的增量ID



我想在Codeigniter中导入excel作为json数据,并生成id。

我的型号

public function generateImpId() {
$now = date('ymd');
$check = "SELECT COUNT(*) as count FROM OP_IMP_15 WHERE DATE(OP_IMP_15.created_at) = DATE(NOW())";
$querycheck = $this->db->query($check);
$id = $querycheck->row()->count;
return 'IMPDEMO'.$now.str_pad($id, 4, '0', STR_PAD_LEFT);
}

我的控制器

//count row
$lastRow = $objPHPExcel->setActiveSheetIndex($sheetnumber)->getHighestRow();       
$countrow = $lastRow - 1;
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$myArray[] = array(
'site_id' => $objWorksheet->getCell('C'.$j)->getValue(),
'site_name' => $objWorksheet->getCell('D'.$j)->getValue(),
'id_site_doc'=> $objWorksheet->getCell('J'.$j)->getValue(),
'id_project_doc' => $objWorksheet->getCell('K'.$j)->getValue(),
//generate ID from model
'implementation_id' => $this->M_MRCR_A->generateImpId(),
...

结果

{      "site_id":"AR001",
"site_name":"Site AR 001",
"id_site_doc":"5df1b4223269f818adab55af",
"id_project_doc":"5da43895e619143bcff53ab1",
"implementation_id":"IMPDEMO2003310001",
"status":"implementation_created",
"endstate":false,
"created_by":"sgph_pm@mittapp.com",
"counter_mr":"0",
"tech_boq_ids":[

],
...
{      "site_id":"AR002",
"site_name":"Site AR 002",
"id_site_doc":"5df1b4223269f818adab55af",
"id_project_doc":"5da43895e619143bcff53ab2",
"implementation_id":"IMPDEMO2003310001",
"status":"implementation_created",
"endstate":false,
"created_by":"sgph_pm@mittapp.com",
"counter_mr":"0",
"tech_boq_ids":[

],

我的期望

使"implementation_id"根据将导入的数据行数递增,并使格式基于我制作的自定义id(我不能使用uuid(。例如:我有3行要导入,所以$implementation_id的值将是:IMPDEMO2003310001、IMPDEMO22003310002、IMPDEMO2003310003

因为您已经有了生成的implementation_id值,而我不知道generateImpId()函数的作用,所以您可以手动将每个生成的implementation_id替换为您拥有的$j

//count row
$lastRow = $objPHPExcel->setActiveSheetIndex($sheetnumber)->getHighestRow();       
$countrow = $lastRow - 1;
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$implementation_id = $this->M_MRCR_A->generateImpId();
$implementation_id = substr($implementation_id, 0, -4) . str_pad($j-1, 4, '0', STR_PAD_LEFT); // since $j starts with 2
$myArray[] = array(
'site_id' => $objWorksheet->getCell('C'.$j)->getValue(),
'site_name' => $objWorksheet->getCell('D'.$j)->getValue(),
'id_site_doc'=> $objWorksheet->getCell('J'.$j)->getValue(),
'id_project_doc' => $objWorksheet->getCell('K'.$j)->getValue(),
//generate ID from model
'implementation_id' => $implementation_id,
...

你不应该试图在一个循环中完成所有事情。

也许您应该使用第一次迭代(for循环(来创建数组,然后使用第二次迭代来填充implementation_id字段。

您可以通过在循环开始时获取开始实现ID来实现这一点,并每次递增(PHP可以处理这样的字符串递增(。。。

$implementationID = $this->M_MRCR_A->generateImpId();
//start loop excel from 2nd row. Row 1 is title row
for ($j=2; $j < $lastRow; $j++ ){
$myArray[] = array(
// ...
//generate ID from model
'implementation_id' => $implementationID++,

这应该会给你一些价值观,比如。。。

IMPDEMO2003310001
IMPDEMO2003310002
IMPDEMO2003310003

最新更新