Php 比较csv列名与csv标题数组

Php 比较csv列名与csv标题数组,php,laravel,csv,Php,Laravel,Csv,很抱歉,我正在编辑我的问题。我真正的问题是如何在fillMapArray函数的$csv_列_名称与readRow函数中存储在$csv_头_数组中的值之间执行比较。此问题与“两个csv一个表”问题有关,因为存储csv列名的映射表中加载了两个csv文件 public $table; public $filename; public $insert_chunk_size = 500; public $csv_delimiter = ','; public $offset_rows = 1; // Ar

很抱歉,我正在编辑我的问题。我真正的问题是如何在fillMapArray函数的$csv_列_名称与readRow函数中存储在$csv_头_数组中的值之间执行比较。此问题与“两个csv一个表”问题有关,因为存储csv列名的映射表中加载了两个csv文件

public $table;
public $filename;
public $insert_chunk_size = 500;
public $csv_delimiter = ',';
public $offset_rows = 1;
// Array to store Database column names
public $mapping = [];
public function setTableName($tablename)
{
    $this->table = $tablename;
}
public function setFileName($filename)
{
    $this->filename = $filename;
}
public function setColumnMapping()
{
    //Retrieve the column names of the table
    // and store them in the array
    $columns = Schema::getColumnListing($this->table);
    $i = 0;
    while ($i < (sizeof($columns) - 1)) {
        array_push($this->mapping, $columns[$i+1]);
        $i++;
    }
}
public function openCSV($filename)
{
    if (!file_exists($filename) || !is_readable($filename)) {
        Log::error("CSV insert failed" . $filename . "does not exist or is not readable");
    }
    $handle = fopen($filename, 'r');
    return $handle;
}
public function seedFromCSV($filename, $deliminator = ',')
{
    $handle = $this->openCSV($filename);
    // CSV doesn't exist or couldn't be read from.
    if ( $handle === FALSE )
        return [];
    $header = NULL;
    $row_count = 0;
    $data = [];
    // Array to store CSV Header column names
    $Csv_header_array = [];
    $mapping = $this->mapping ?: [];
    $offset = $this->offset_rows;
    while ( ($row = fgetcsv($handle, 0, $deliminator)) !== FALSE )
    {
        // Offset the specified number of rows
        while ( $offset > 0 )
        {
            //If the row being read is the first,
            //store the CSV header names in the array
            $index = 0;
            while ($index < sizeof($row)) {
                array_push($Csv_header_array, $row[$index]);
                $index++;
            }
            $offset--;
            continue 2;
        }
        // No mapping specified - grab the first CSV row and use it
        if ( !$mapping )
        {
            $mapping = $row;
        }
        else
        {
            // Array to store a map of CSV column headers
            // to the corresponding values
            $source_array = $this->readRow($row, $Csv_header_array);
            // Create a map of database column names to
            // the corresponding values
            $row = $this->fillMapArray($source_array, $mapping);
            // insert only non-empty rows from the csv file
            if ( !$row )
                continue;
            $data[$row_count] = $row;
            // Chunk size reached, insert
            if ( ++$row_count == $this->insert_chunk_size )
            {
                //var_dump($this->insert($data));
                $this->insert($data);
                $row_count = 0;
                //var_dump($data[0]);
                // clear the data array explicitly to
                // avoid duplicate inserts
                $data = array();
            }
        }
    }
    // Insert any leftover rows
    if ( count($data)  )
        $this->insert($data);
    fclose($handle);
    return $data;
}
public function readRow( array $row, array $Csv_header_array )
{
    // Read the values of CSV column headers and map them
    // into an array
    $source_array = [];
    foreach ($Csv_header_array as $index => $csvCol) {
        if (!isset($row[$index]) || $row[$index] === '') {
            $source_array[$csvCol] = NULL;
        }
        else {
            $source_array[$csvCol] = $row[$index];
        }
    }
    return $source_array;
}
public function fillMapArray($source_array, $mapping) {
    $row_values = [];
    $columns = Schema::getColumnListing('maps');
    $no_of_columns_to_fill = sizeof($source_array);
    // Retrieve the CSV column header corresponding to
    // the Database column and store in a map
    foreach($mapping as $dbCol) {
        if ($dbCol === 'year') {
            $row_values[$dbCol] = 2014;
        } else {
            if ($dbCol === 'School_ID') {
                $temp1 = DB::Table('schools')->where('Unit_Id', '=',
                    $source_array['UNITID'])->value('School_ID');
                $row_values[$dbCol] = $temp1;
            } else {
                if ($no_of_columns_to_fill > 0) {
                    $csv_Column_name = DB::Table('maps')->where($columns[3], '=', $this->table)
                        ->where($columns[1], $dbCol)->value($columns[2]);
                    if ($csv_Column_name === Null) {
                        $no_of_columns_to_fill--;
                    } else {
                        $row_values[$dbCol] = $source_array[$csv_Column_name];
                        $no_of_columns_to_fill--;
                    }
                }
            }
        }
    }
    //var_dump($row_values);
    return $row_values;
}
public function insert( array $seedData )
{
    try {
        DB::table($this->table)->insert($seedData);
    } catch (\Exception $e) {
        Log::error("CSV insert failed: " . $e->getMessage() . " - CSV " . $this->filename);
        return FALSE;
    }
    return TRUE;
}
public$表;
public$filename;
公共$insert\u chunk\u size=500;
公共$csv_分隔符=',';
公共$offset_行=1;
//用于存储数据库列名的数组
公共$mapping=[];
公共函数setTableName($tablename)
{
$this->table=$tablename;
}
公共函数setFileName($filename)
{
$this->filename=$filename;
}
公共函数setColumnMapping()
{
//检索表的列名
//并将它们存储在数组中
$columns=Schema::getColumnListing($this->table);
$i=0;
而($i<(sizeof($columns)-1)){
数组推送($this->mapping,$columns[$i+1]);
$i++;
}
}
公共函数openCSV($filename)
{
如果(!file_存在($filename)| |!是否可读($filename)){
日志::错误(“CSV插入失败”。$filename。“不存在或不可读”);
}
$handle=fopen($filename,'r');
返回$handle;
}
公共函数seedFromCSV($filename,$deliminator=','))
{
$handle=$this->openCSV($filename);
//CSV不存在或无法从中读取。
如果($handle==FALSE)
返回[];
$header=NULL;
$row\U count=0;
$data=[];
//用于存储CSV标题列名的数组
$Csv_头_数组=[];
$mapping=$this->mapping?:[];
$offset=$this->offset\u行;
while(($row=fgetcsv($handle,0,$deliminator))!==FALSE)
{
//偏移指定的行数
而($offset>0)
{
//如果正在读取的行是第一行,
//将CSV头名称存储在数组中
$index=0;
而($indexreadRow($row,$Csv\u header\u array);
//创建数据库列名到的映射
//相应的值
$row=$this->fillMapArray($source\u array,$mapping);
//仅插入csv文件中的非空行
如果(!$row)
继续;
$data[$row\U count]=$row;
//已达到块大小,请插入
如果(++$row\u count==$this->insert\u chunk\u size)
{
//变量转储($this->insert($data));
$this->insert($data);
$row\U count=0;
//var_dump($data[0]);
//明确清除数据数组以
//避免重复插入
$data=array();
}
}
}
//插入任何剩余的行
如果(计数($数据))
$this->insert($data);
fclose($handle);
返回$data;
}
公共函数readRow(数组$row,数组$Csv\u头\u数组)
{
//读取CSV列标题的值并将其映射
//排成一列
$source_array=[];
foreach($Csv\u header\u数组作为$index=>$csvCol){
如果(!isset($row[$index])| |$row[$index]=''){
$source_数组[$csvCol]=NULL;
}
否则{
$source_数组[$csvCol]=$row[$index];
}
}
返回$source_数组;
}
公共函数fillMapArray($source\u array,$mapping){
$row_值=[];
$columns=Schema::getColumnListing('maps');
$no_of_columns_to_fill=sizeof($source_数组);
//检索对应于的CSV列标题
//数据库列和存储在映射中
foreach($dbCol映射){
如果($dbCol=='year'){
$row_值[$dbCol]=2014;
}否则{
如果($dbCol=='School\u ID'){
$temp1=DB::Table('schools')->其中('Unit_Id','=',
$source_数组['UNITID'])->值('School_ID');
$row_值[$dbCol]=$temp1;
}否则{
如果($no_of_columns_to_fill>0){
$csv_Column_name=DB::Table('maps')->其中($columns[3],'=',$this->Table)
->其中($columns[1],$dbCol)->值($columns[2]);
如果($csv\u列\u名称===Null){
$no_of_columns_to_fill--;
}否则{
$row_values[$dbCol]=$source_数组[$csv_Column_name];
$no_of_columns_to_fill--;
}
}
}
}
}
//变量转储(行值);
返回$row_值;
}
公共函数插入(数组$seedData)
{
试一试{
DB::table($this->table)->insert($seedData);
}捕获(\异常$e){
日志::错误(“CSV插入失败:”.e->getMessage()。“-CSV”。$this->filename);
返回FALSE;
}
返回TRUE;
}
}

您可以使用软件包获取CSV数据,然后将其映射到Elounce模型。示例:如果您的CSV表是
用户
,则您的模型将是
用户

所以您可以从CSV中提取所有数据,然后将其映射到模型

// This array will be created with the help of Laravel-Excel package
$users = array(
    array('name'=>'Coder 1', 'rep'=>'4096'),
    array('name'=>'Coder 2', 'rep'=>'2048'),
    //...
);

// your second CSV file will also perform similar task and map it to same array
$users[] = ['name' => 'Coder 3'];

// Start bulk insert
User::insert($users);
您可以使用包获取CSV数据,然后将其映射到Elounce模型。示例:如果您的CSV表是
用户
,则您的模型将是
用户

所以您可以从CSV中提取所有数据,然后将其映射到模型

// This array will be created with the help of Laravel-Excel package
$users = array(
    array('name'=>'Coder 1', 'rep'=>'4096'),
    array('name'=>'Coder 2', 'rep'=>'2048'),
    //...
);

// your second CSV file will also perform similar task and map it to same array
$users[] = ['name' => 'Coder 3'];

// Start bulk insert
User::insert($users);