gpt4 book ai didi

php - laravel foreach 循环仅将数组的最后一个元素存储在数据库表中

转载 作者:行者123 更新时间:2023-11-29 01:53:30 27 4
gpt4 key购买 nike

我的 Controller 中有一个函数,它使用 php excel 从 excel 文件中读取行,并将其存储到 db 表中。

public function processData(Request $request)
{
/* store data from form in to variables */
$hotel = $request->input('hotel');
$date = $request->input('date');
$start_row = $request->input('row');
$date_col = $request->input('date-col');
$sold_col = $request->input('sold-col');
$rev_col = $request->input('rev-col');

/* get tables name */
$table = str_replace('-', '_', $hotel);
$monthly_table = $table . '_monthly';

/* init hotel class */
$hotel_table = new Hotel($table);

$file = public_path().'/'.$date.'.xls';

$sheetData = Excel::load($file)->noHeading()->getExcel()->getSheet()->toArray(null,false,false, true);
$sheetData = array_slice($sheetData, $start_row - 1);

foreach ($sheetData as $row)
{
if ($this->isDate($row[$date_col]))
{
print $row[$date_col] . "---" . $row[$sold_col] . "---" . gettype(money_format('%i', floatval($row[$rev_col]))) . "<br>";
$hotel_table->date = $row[$date_col];
$hotel_table->sold = intval($row[$sold_col]);
$hotel_table->sold_diff = 0;
$hotel_table->rev = floatval($row[$rev_col]);
$hotel_table->rev_diff = 0;
$hotel_table->row = $start_row;
$hotel_table->date_col = $date_col;
$hotel_table->sold_col = $sold_col;
$hotel_table->rev_col = $rev_col;
//$hotel_table->save();
if (!$hotel_table->save())
{
dd ( DB::getQueryLog() );
}

}
}

}

public function isDate($date)
{
if (date('m/d/Y', strtotime($date)) == $date)
{
return true;
}
else
{
return false;
}
}

这是我的 table

Schema::create($tableName, function (Blueprint $table) {
$table->increments('id');
$table->string('date');
$table->integer('sold');
$table->integer('sold_diff');
$table->float('rev');
$table->float('rev_diff');
$table->string('row');
$table->string('date_col');
$table->string('sold_col');
$table->string('rev_col');
$table->timestamps();
});

当我通过 foreach 时,它在屏幕上打印的东西很好,没有错误,但是当我查看表时,它只有数据库表中数组的最后一个元素。

最佳答案

如果 Hotel 类是您的模型,那么您需要在 foreach block 中移动以下代码

foreach ($sheetData as $row)
{
if ($this->isDate($row[$date_col]))
{
$hotel_table = new Hotel($table);
...
}
}

关于php - laravel foreach 循环仅将数组的最后一个元素存储在数据库表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com