我从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数组"列表"中删除重复项。
我正在使用:
$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);
}
}
正如文档中所解释的,array_unique
默认情况下将元素作为字符串进行比较。您收到此错误是因为PHP正试图将数组转换为字符串。你有一个二维数组,一个数组的数组。
您可以使用标志SORT_REGULAR
对元素进行原样比较。但要小心,只有相同的键/值对才被认为是相同的。
在SELECT语句中使用UNION可以大大减少代码量。
SELECT field FROM table1
UNION
SELECT field FROM table2
UNION
SELECT field FROM table3
UNION
SELECT field FROM table4
默认情况下,UNION返回不同的结果。
成功了:
$list = array_map("unserialize", array_unique(array_map("serialize", $list)));
$list
是一个2d阵列。