我正在嘗試瀏覽CSV檔案并提取其所有內容。
內容匯入后,我需要將它們插入到我的mysql資料庫表中,但在這之前我需要檢查這些記錄是否存在。如果一條記錄不存在,就匯入這個注冊表。
我有一個頭像,我想把它放到我的資料庫中。
我已經得到了標題和所有內容,我已經用這些資訊創建了一個陣列,但我不知道它是否100%正確。這是我的實際代碼:
function csv_content_parser($content) {
foreach (explode("
"/span>, $content) as $line) {
//span>生成器保存狀態,當需要下一個值時可以恢復。
yield str_getcsv($line)。
}
}
$archivo = fopen($route, "r") 。
//從csv檔案中獲取內容。。
$content = file_get_contents($adjunto)。
//從csv檔案的行中創建陣列。
$data = array();
$headers = array();
$rows = array();
//獲取所有內容。
foreach ($this->csv_content_parser($content) as $fields) {
array_push($data, $fields) 。
}
//get headers; }
foreach($data[0] as $dat){
array_push($headers, $dat) 。
}
//get all content of csv without headers; }
for($i=1; $i<count($data); $i ){
array_push($rows, $data[$i] )。)
}
//關閉檔案。
fclose($archivo)。
csv檔案的內容(這是一個例子檔案)為例(我需要創建一個通用的匯入器):
Array
(
[0] => Array[/span
(
[0] => [email protected]
[1] => david
[2] => 005] => david
[3] => hola
[4] => eee
[5] => eee
)
[1] =>Array] => eee
(
[0] => [email protected]
[1] => david
[2] => 005] => david
[3] => hola
[4] => eee
[5] => eee
)
)
而我的頭檔案:
Array
(
[0] => Email
[1] => 名字
[2] => 身份證
[3] => 備注
[4] => 欄位標簽 1] =>注解
[5] => 欄位標簽2。
)
我的問題是:這是否是一個好的解決方案,或者有什么更好的解決方案可以做到這一點?我需要將這些資料插入到我的資料庫中。如何才能做到這一點呢?
更新內容:
model
<?php
namespace App。
使用 IlluminateDatabaseEloquentModel。
class Listado extends Model
{
protected $table = 'listado';
protected $fillable = [
'nomape', 'direccion', 'provincia', 'ciudad', 'cp'/span>, 'telefono'/span>, 'movil'/span>, 'id_teleoperadora'.
];
/**。
* 對于陣列來說,應該被隱藏的屬性。
*
* @var array
*/
protected $hidden = [];
public function scopeTodos($query )
{
return $query->orderBy('nomape'/span>, 'ASC'/span>)-> orderBy('telefono', 'ASC') 。
}
public function scopeSinAsignar($query, $id_llamadas )
{
$query->whereIn('id', $id_llamadas)->whereNull('id_teleoperadora')。
}
public static function Filtrado($request)
{
$query = self::query();
if($request['direccion']) {
$query->where('direccion', 'like', '%' . $request['direccion'] 。'%')。)
}
if($request['ciudad']) {
$query->where('ciudad', $request['ciudad']) 。
}
if($request['cp']) {
$query->where('cp', $request['cp'] )。)
}
/*if($request['teleoperadora'] ) {
$query->where('id_teleoperadora', $request['teleoperadora']) 。
}*/
return $query。
}
public function scopeConEstado( $query, $nombreEstado)
{
return $query->whereHas('llamada. estado'。function ($query). 變數">$query) use ($nombreEstado) {
$query->whereNombre($nombreEstado)。
})->orWhereDoesntHave('llamada')。
}
public function scopeConEstados($query, $nombresEstado)
{
return $query->whereHas('llamada. estado'。function ($query). 變數">$query) use ($nombresEstado) {
$query->whereIn('nombre', $nombresEstado) 。
})->或者WhereDoesntHave('llamada')。
}
public function llamada()
{
return $this-> hasOne('AppLlamada', 'id_listado', 'id')-> latest();
}
public function llamada_test()
{
return $this->hasOne('AppLamada', 'id', 'id_listado') 。
}
/**。
*回傳操作者
*/
public function teleoperadora()
{
return $this-> hasOne('AppUser'/span>, 'id'/span>, 'id_teleoperadora'/span>)-> withDefault(['nombre' => 'NINGUNA'])。
}
/***。
*回傳呼叫資料
*/
public function callStatusName()
{
return $this->hasOne('Appllamada'/span>, 'id_listado'/span>, 'id') 。
}
}
更新2
我所有的函式代碼
function csv_content_parser($content) {
foreach (explode("
"/span>, $content) as $line) {
//span>生成器保存狀態,當需要下一個值時可以恢復。
yield str_getcsv($line)。
}
}
public function uploadListing(Request $request)
{
$adjunto = $request->file('attach')。
$route = ""。
if(isset($adjunto)){
$name = $adjunto->getClientOriginalName()。
$result = $adjunto-> storeAs('importaciones'/span>, $name, 's4')。
$route = public_path('storage/importaciones/'.$name) 。
}else{
return "Error al adjuntar recibo de envío, consulte al administrador del sistema" ;
}
//Abrimos nuestro archivo.
$archivo = fopen($route, "r") 。
//從csv檔案中獲取內容。。
$content = file_get_contents($adjunto)。
//從csv檔案的行中創建陣列。
$data = array();
$headers = array();
$rows = array();
//獲取所有內容。
foreach ($this->csv_content_parser($content) as $fields) {
array_push($data, $fields) 。
}
//get headers; }
foreach($data[0] as $dat){
array_push($headers, $dat) 。
}
//get all content of csv without headers; }
for($i=1; $i<count($data); $i ){
array_push($rows, $data[$i] )。)
}
Listado::insertOrIgnore(array_map(function($row) /span>{
return array_combine($headers, $row)。
}, $rows) )。
//Cerramos el archivo
fclose($archivo)。
}
更新3
function csv_content_parser(span class="hljs-variable">$content) {
foreach (explode("
"/span>, $content) as $line) {
//span>生成器保存狀態,當需要下一個值時可以恢復。
yield str_getcsv($line)。
}
}
public function uploadListing(Request $request)
{
$adjunto = $request->file('attach')。
$route = ""。
if(isset($adjunto)){
$name = $adjunto->getClientOriginalName()。
$result = $adjunto-> storeAs('importaciones'/span>, $name, 's4')。
$route = public_path('storage/importaciones/'.$name) 。
}else{
return "Error al adjuntar recibo de envío, consulte al administrador del sistema" ;
}
//Abrimos nuestro archivo.
$archivo = fopen($route, "r") 。
//從csv檔案中獲取內容。。
$content = file_get_contents($adjunto)。
//從csv檔案的行中創建陣列。
$data = array();
$headers = array();
$rows = array();
//獲取所有內容。
foreach ($this->csv_content_parser($content) as $fields) {
array_push($data, $fields) 。
}
//get headers; }
foreach($data[0] as $dat){
array_push($headers, $dat) 。
}
//get all content of csv without headers; }
for($i=1; $i<count($data); $i ){
array_push($rows, $data[$i] )。)
}
Listado:: insertOrIgnore(array_map(function($row) 變數">$row) use($headers) {
return array_combine($headers, $row) 。
}, $rows) )。
//Cerramos el archivo
fclose($archivo)。
}
uj5u.com熱心網友回復:
如per docs:
DB:: table('listado')->insertOrIgnore(array_map(fn($row>) => array_combine($headers, $row), $rows) )。
由于你有Eloquent模型,你可以使用Eloquent的insert()方法:
Listado:: insertOrIgnore(array_map(fn($row) => array_combine($headers, $row), $rows) )。
既然你說了以下的話
我需要檢查這些記錄是否存在。如果一個記錄不存在,就匯入這個注冊表。
我選擇了insertOrIgnore()的方法, 但也許你想要別的東西。幸運的是,Laravel有一堆類似的方法,用于稍微不同的使用情況。
在PHP7.4之前, array_map(fn($row) => array_combine($headers, $row), $rows) 必須是:
array_map(function($row) use($headers) {
return array_combine($headers, $row) 。
}, $rows)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/320629.html
標籤:
