从PHP数组中删除重复项(array_unique)

时间:2016-01-06 15:57:58

标签: php array-unique

我从4个不同的表中获取特定字段。

<?php 

//I connect to the database and the 4 tables

// Location of CSV  
$location = 'path.csv';

// List creation that will be updated with the fields and be put into my CSV file
$list = array();

// Read csv file to avoid adding duplicates
$file = fopen($location, 'r');
$data = array();

while($row = fgetcsv($file)) 
{
   $data[] = $row;
}

// Query 1
$sql = ('select distinct(field) as field from '.$table1.'');

// Run the query
$query = $Db->query($sql);

// Check for SQL errors
if ($Db->error) 
{
    return ($Db->error);
}

// Put data in the list
while ($row = $query->fetch_assoc()) 
{
    array_push($list,array($row['field'], ''));
}

// Query 2
$sql = ('select distinct(field) as field from '.$table2.'');

// Run the query
$query = $Db->query($sql);

// Check for SQL errors
if ($Db->error) 
{
    return ($Db->error);
}

// Put data in the list
while ($row = $query->fetch_assoc()) 
{
    array_push($list,array($row['field'], ''));
}

// Query 3
$sql = ('select distinct(field) as field from '.$table3.'');

// Run the query
$query = $Db->query($sql);

// Check for SQL errors
if ($Db->error) 
{
    return ($Db->error);
}

// Put data in the list
while ($row = $query->fetch_assoc()) 
{
    array_push($list,array($row['field'], ''));
}

// Query 4
$sql = ('select distinct(field) as field from '.$table4.'');

// Run the query
$query = $Db->query($sql);

// Check for SQL errors
if ($Db->error) 
{
    return ($Db->error);
}

// Put data in the list
while ($row = $query->fetch_assoc()) 
{
    array_push($list,array($row['field'], ''));
}


// Save list in the csv file without overwriting
$fp = fopen($location, 'a');

foreach (array_unique($list) as $fields) 
{
    if (in_array($fields, $data)) 
    {
        echo "Duplicate found";
    }
    else
    {
        echo "Save to file";
        fputcsv($fp, $fields);
    }           
}

fclose($fp);    

?>

最后,我检查字段是否已存在于文件中。唯一的问题是我仍然有重复项,因为某些表可能具有完全相同的字段。所以,我想从PHP数组&#34; list&#34;中删除重复项。

我正在使用:

$cleanlist = array_unique($list);

但是我收到了一个错误:

  

PHP注意:数组转换为字符串

更具体地说,我的代码更改为:

    $cleanlist = array_unique($list);

// Save list in the csv file without overwriting
$fp = fopen($location, 'a');

foreach ($cleanlist as $fields) 
{
    if (in_array($fields, $data)) 
    {
        echo "Duplicate found";
    }
    else
    {
        echo "Save to file";
        fputcsv($fp, $fields);
    }           
}

3 个答案:

答案 0 :(得分:2)

正如the docs中的解释,array_unique默认情况下将元素作为字符串进行比较。您收到此错误是因为PHP正在尝试将Array转换为字符串。你有一个2D数组,一个数组数组。

您可以使用标记SORT_REGULAR来比较元素。 但要小心,只有相同的键/值对被认为是相同的。

答案 1 :(得分:1)

在SELECT语句中使用UNION可以减少很多代码。

SELECT field FROM table1
UNION
SELECT field FROM table2
UNION
SELECT field FROM table3
UNION
SELECT field FROM table4

UNION默认返回不同的结果。

答案 2 :(得分:0)

有效:

$list = array_map("unserialize", array_unique(array_map("serialize", $list)));

$list是一个二维数组。