我想将每个用户添加到一个数组中,并在执行之前检查是否有重复项。
$spotcount = 10;
for ($topuser_count = 0; $topuser_count < $spotcount; $topuser_count++) //total spots
{
$spottop10 = $ids[$topuser_count];
$top_10 = $gowalla->getSpotInfo($spottop10);
$usercount = 0;
$c = 0;
$array = array();
foreach($top_10['top_10'] as $top10) //loop each spot
{
//$getuser = substr($top10['url'],7); //strip the url
$getuser = ltrim($top10['url'], " users/" );
if ($usercount < 3) //loop only certain number of top users
{
if (($getuser != $userurl) && (array_search($getuser, $array) !== true))
{
//echo " no duplicates! <br /><br />";
echo ' <a href= "http://gowalla.com'.$top10['url'].'"><img width="90" height="90" src= " '.$top10['image_url'].' " title="'.$top10['first_name'].'" alt="Error" /></a> ';
$array[$c++] = $getuser;
}
else {
//echo "duplicate <br /><br />";
}
}
$usercount++;
}
print_r($array);
}
之前的代码打印:
Array ( [0] => 62151 [1] => 204501 [2] => 209368 )
Array ( [0] => 62151 [1] => 33116 [2] => 122485 )
Array ( [0] => 120728 [1] => 205247 [2] => 33116 )
Array ( [0] => 150883 [1] => 248551 [2] => 248558 )
Array ( [0] => 157580 [1] => 77490 [2] => 52046 )
这是错误的。它确实检查重复项,但仅检查每个 foreach 循环的内容,而不是整个数组。如果我将所有内容都存储到 $array 中,会怎么样?
array_search()
返回您要搜索的内容的键(如果它在数组中)。您正在对 !==
与 true
进行严格的不等式比较,因此,如果 array_search 确实在数组中找到了一个条目(例如,键是 7),则 7 !== TRUE
为 true,然后您继续将该条目添加到您的数组中。新数组。
您想要的是
array_search(...) !== FALSE
,只有在 array_search 失败时才会计算为 true。
此外,无需使用
$c++
数组索引计数器。您可以使用 $array[] = $getuser
它将自动将 $getuser 粘贴到数组末尾的新条目中。
对多维数组使用以下函数
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom] == $elem)
return true;
else
if(is_array($array[$bottom]))
if(in_multiarray($elem, ($array[$bottom])))
return true;
$bottom++;
}
return false;
}
有关更多信息,请参阅 in_array()
更快、更清晰递归多维数组搜索,使用标准 PHP 库 (SPL)。
function in_array_recursive($needle, $haystack) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack));
foreach($it as $element) {
if($element == $needle) {
return true;
}
}
return false;
}