2016-01-06 68 views
0

我從4個不同的表中獲取特定字段。從PHP陣列中刪除重複項(array_unique)

<?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數組「list」中刪除重複項。

我使用:

$cleanlist = array_unique($list); 

但我得到一個錯誤:

PHP Notice: Array to string conversion

更具體地在我的代碼的變化是:

$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); 
    }   
} 

回答

1

通過在SELECT語句中使用UNION,可以大量減少代碼量。

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

UNION默認返回不同的結果。

+0

偉大的解決方案。它可以節省大量的線路!我也發佈了一個答案,但你更好。 Mine只是將array_unique用於n維表的一種方式。 –

2

the docs解釋, array_unique默認情況下將元素作爲字符串進行比較。你正在得到這個錯誤,因爲PHP試圖將一個數組轉換爲字符串。你有一個二維數組,一個數組。

您可以使用標誌SORT_REGULAR比較它們的元素。 但要小心,只有相同的鍵/值對被認爲是相同的。

0

這一工作:

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

$list是2D陣列。