您好,我有一个接收数组的函数,它为数组中的每个元素运行一个查询,该查询选择一个随机的结果id,但是我想避免重复,我如何检查结果id是否重复并再次运行查询?都在循环中而不是跳过元素?下面是我的尝试(注意:$array_result是7个元素),select distinct也不起作用,因为我必须分别为每个数组元素运行查询
$queryn = "select taxonomic_units.tsn, hierarchy.hierarchy_string, hierarchy.TSN, taxonomic_units.rank_id from hierarchy left join taxonomic_units on hierarchy.TSN = taxonomic_units.tsn where taxonomic_units.rank_id = 220 and hierarchy.hierarchy_string LIKE '%$array_result[0]%'order by rand() limit 1";
$resultn = $dbn -> Execute($queryn);
$rown=$resultn->FetchRow();
$newspecies = $rown['tsn'];
$result_array[] = $newspecies;
for($i=1; $i<count($array_result);$i++){
$previous = implode(',', $result_array);
$queryn = "select taxonomic_units.tsn,
hierarchy.hierarchy_string,
hierarchy.TSN,
taxonomic_units.rank_id
from hierarchy
left join taxonomic_units
on hierarchy.TSN = taxonomic_units.tsn
where taxonomic_units.rank_id = 220
and hierarchy.hierarchy_string LIKE '%$array_result[$i]%'
and taxonomic_units.tsn not in ('$previous')
order by rand()
limit 1";
$resultn = $dbn -> Execute($queryn);
$rown=$resultn->FetchRow();
$newspecies = $rown['tsn'];
$result_array[] = $newspecies;
}发布于 2013-08-07 12:02:28
您可以在存储ID之前搜索重复项。只需使用in_array即可。
function getrandomspecies($array_result){
...
$i=0; //If your $array_result begin with 0
while($i<count($array_result))
{
...
$newspecies = $rown['tsn'];
if(in_array($newspecies, $result_array)))
continue;
else
{
$result_array[] = $newspecies;
$i++;
}
}
}发布于 2013-08-07 12:02:45
您的$array_result结构是什么?
array( ''=>'');
或
数组(数组( '‘=> '') );
如果你的数组结构是1,那么你可以使用array_unique来检查重复的id。
如果您数组结构是第二个数组结构,则在运行查询之前,您可能需要执行一些过滤函数。
发布于 2013-08-07 12:51:08
function getrandomspecies($array_result){
$dbn = adodbConnect(); //connect to database
$result_array = array(); //make empty array for result array
$i=0;
a: foreach($array_result as $id){ // this loops 7 times
for($j=0;$j<=$i;$j++)
{
if($array_result[$j]==$id)
{
goto a; //will go to foreach loop if there is a previous occurence of the element
}
}
//complicated query that basically chooses a random id based on a likeness of a string that has other ids
$queryn = "select taxonomic_units.tsn, hierarchy.hierarchy_string, hierarchy.TSN, taxonomic_units.rank_id from hierarchy left join taxonomic_units on hierarchy.TSN = taxonomic_units.tsn where taxonomic_units.rank_id = 220 and hierarchy.hierarchy_string LIKE '%$id%'order by rand() limit 1";
$resultn = $dbn -> Execute($queryn);
$rown=$resultn->FetchRow();
$newspecies = $rown['tsn'];
$result_array[] = $newspecies; //this is the result array and the one result putting in
} }
https://stackoverflow.com/questions/18094327
复制相似问题