【问题标题】:Unable to compare 2 arrays (case insensitive) in PHP无法在 PHP 中比较 2 个数组(不区分大小写)
【发布时间】:2014-08-13 08:14:16
【问题描述】:

我已在 csv 文件中存储了一个 event_id 列表,其中包含有关这 50 个事件的数据。我有 50 个带有相应 event_id 的 csv 文件,其中包含将参加该活动的 user_id 列表。实际参加该活动的人员列表保存在 mysql DB 中。所以,现在想比较这两个列表,看看谁实际参加了这些活动。但是csv中的数据是大写的,mysql中的数据是小写的。

Master Event CSV File
event_id  event_date
001       x/x/2014
002       x/x/2014
003       x/x/2014

50 event csv files (each file is named after the event_id):

CSV file name: 001.csv
user_id   first_name
cust_123       Chris  
cust_234       John
cust_345       David

所以到目前为止,我所做的是遍历主事件 csv 以获取 event_id,并使用该 event_id,我试图将用户列表存储在 $data 数组中。然后,我从 $checkUser 中的 db 中检索实际出勤列表。最后。我使用 array_intersect 来比较两个数组。

$con= new PDO('mysql:host=localhost;dbname=test',$username,$password);

//Master CSV File containing all user id and user info
$file_handle = fopen($fileName, "r");

//while loop to loop through Master CSV to get the event id
$i = 0;
while ($i < 50) {

    //Get the event id from CSV Master file
    $file_line = fgetcsv($file_handle , 1024);
    $event_id = $file_line[0];

    //open csv file containing user id for each event   
    $csv_handle = fopen("file.csv", "r");

    //Get list of user_id from csv
    $data = array();
    while($row = fgetcsv($csv_handle)) {
    $data[] = $row[0];
}

    //Get list of user_id from mysql
    $sql = $con->prepare("SELECT user_id FROM user WHERE event_date = ");
    $sql -> execute();
    $checkUser = array();
    while($result = $sql ->fetch(PDO::FETCH_ASSOC)) {
        $checkUser = $result['user_id'];
}

    //Compare 2 arrays for matches
    user_intersect = array_intersect($checkUser, $data);

    $i++;
}

?>

我收到以下错误。任何帮助都会很棒。

Notice: Array to string conversion in C:\wamp\www...

【问题讨论】:

  • '$checkUser = ..' 表示在你的情况下变量字符串的确切值.. '$checkUser[] = ..' 表示向数组添加值..

标签: php mysql arrays csv


【解决方案1】:

在这条线上

$checkUser = $result['user_id'];

即使您在while 循环之前将$checkUser 声明为一个数组,它仍充当一个变量,在每次迭代时都会被覆盖,因此只会包含循环中的最后一个值。所以它不是一个数组,而只是一个变量。

为了保持它是一个数组,你需要将它用作:

$checkUser[] = $result['user_id'];

[] 表示当前项正在添加到现有数组中,而不是覆盖它。

编辑

为了使用不区分大小写的值,您可以使用array_map

$user_intersect = array_intersect(
                     array_map('strtolower', $checkUser), 
                     array_map('strtolower', $data)
                   );

【讨论】:

  • array_intersect 可以处理不区分大小写的数据吗?
猜你喜欢
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-11
  • 2011-05-28
  • 1970-01-01
相关资源
最近更新 更多