【问题标题】:php array_intersect don't get the first valuephp array_intersect 没有得到第一个值
【发布时间】:2019-07-29 16:42:31
【问题描述】:

基本上,我正在尝试将 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"
}

【问题讨论】:

  • 空间或其他东西。通过 var_export() 输出两者
  • 一般来说,var_dump()print_r() 更适合调试。它显示了更多详细信息,可以帮助您查看问题。
  • 我更新了问题,结果很奇怪。为什么会这样?
  • 通知标题是string(8) "email" - 上次我数“电子邮件”有 5 个字符 - 隐藏你的问题
  • 我知道问题,但我无法解决。 trim() 不工作

标签: php arrays array-intersect


【解决方案1】:

php 中的trim() function 默认只截断 6 个不可打印字符。我认为这是您的问题,因为有更多不可打印的字符 (list of characters)。

例如:

<?php

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

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

<?php 

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

正则表达式没有使用 trim(),而是提供了更多的保证:

<?php

// preg_replace('/[\x00-\x1F\x7F]/u', '', $value)
$headers = array_filter(array_map(function($value) { return strtolower(preg_replace('/[\x00-\x1F\x7F]/u', '', $value)); }, $reader->fetchOne()));

【讨论】:

猜你喜欢
  • 2013-07-25
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
相关资源
最近更新 更多