我從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);
}
}
偉大的解決方案。它可以節省大量的線路!我也發佈了一個答案,但你更好。 Mine只是將array_unique用於n維表的一種方式。 –