php array_intersect没有得到第一个值

时间:2019-03-07 17:38:07

标签: php arrays array-intersect

基本上,我正在尝试将csv数据导入到我的数据库中。在将数据插入数据库之前,我要检查数据库是否具有该列(来自csv标头)。

        // read csv from file ex: data.csv
        $reader = \League\Csv\Reader::createFromPath($file);            

        // get first row from csv as headers (email, first_name, last_name etc.)
        $headers = array_filter(array_map(function($value) { return strtolower(trim($value)); }, $reader->fetchOne()));

        // get fields from database (email, first_name, last_name, birthdate etc.)
        $fields = collect($this->fields)->map(function ($field) {
            return strtolower($field->tag);
        })->toArray();


        // want to check which fields has csv
        $availableFields = array_intersect($headers, $fields);

但是,当我运行上面的代码时,array_intersect无法正常工作。

输出为:

 $headers : Array ([0] => email [1] => first_name [2] => last_name ) 

 $fields : Array ( [0] => email [1] => first_name [2] => last_name     [3] => telephone     [4] => gender     [5] => birthdate     [6] => country  ) 

 $availableFields :Array ([1] => first_name [2] => last_name ) 

var_dump的结果是:

$headers : array(3) {
  [0]=>
  string(8) "email"
  [1]=>
  string(10) "first_name"
  [2]=>
  string(9) "last_name"
}
$fields : array(9) {
  [0]=>
  string(5) "email"
  [1]=>
  string(10) "first_name"
  [2]=>
  string(9) "last_name"
  [3]=>
  string(9) "telephone"
  [4]=>
  string(6) "gender"
  [5]=>
  string(9) "birthdate"
  [6]=>
  string(7) "country"
}

1 个答案:

答案 0 :(得分:0)

默认情况下,PHP中的trim() function仅截断6个不可打印的字符。我认为这是您的问题,因为存在更多不可打印的字符(list of characters)。

例如:

skip()

trim()允许您在第二个参数中指定字符掩码:

<?php

var_dump([trim("EMAIL\x1C")]);

与使用trim()相比,正则表达式提供了更多隔离:

<?php 

trim($binary, "\x00..\x1F");