一直试图找出这个简单的问题3天,并且不明白为什么该函数只删除了一些值,但保留了其他值。
这是函数根据好域列表检查坏域列表,如果找到坏域,则将其从好域列表中删除。
这是我的代码:
// check each bad domain, against each array in good array list
$bad_domains = array('youtube.com', 'facebook.com', 'google.com', 'twitter');
$good_domains = array(
'http://www.wufoo.com/',
'https://plus.google.com/u/0/b/105790754629987588694',
'http://studioduplateau.com/ss=',
'http://twitter.com/?lang=tic-toc',
'http://twitter.com/?lang=KA-BOOM',
'http://twitter.com/?lang=tic-toc',
'http://twitter.com/?lang=KA-BOOM',
'http://twitter.com/?lang=tic-toc',
'http://twitter.com/?lang=KA-BOOM',
'http://twitter.com/?lang=tic-toc',
'http://twitter.com/?lang=KA-BOOM',
'http://twitter.com/?lang=KA-BOOM',
'lastofthemohicans.com'
);
function remove_excluded_domains($good_domains, $bad_domains) {
for($x=0; $x<count($bad_domains); $x++)
{
for($y=0; $y<count($good_domains); $y++)
{
if(strpos($good_domains[$y], $bad_domains[$x]))
{
unset($good_domains[$y]);
$good_domains = array_values($good_domains);
}
}
}
return $good_domains;
}
$spider_array = remove_excluded_domains($good_domains, $bad_domains);
由于某种原因它返回:
[0] => http://www.wufoo.com/
[1] => http://studioduplateau.com/ss=
[2] => http://twitter.com/?lang=KA-BOOM
[3] => http://twitter.com/?lang=KA-BOOM
[4] => http://twitter.com/?lang=KA-BOOM
[5] => http://twitter.com/?lang=KA-BOOM
[6] => lastofthemohicans.com
所以它删除了所有 http://twitter.com/?lang=tic-toc ,但保留了所有 http://twitter.com/?lang=KA-BOOM ..
为什么这样做?我尝试使用array_values,但它仍然不起作用。
很抱歉这些愚蠢的数组值,只是想让它脱颖而出,所以它更清晰。感谢您的帮助。
答案 0 :(得分:2)
问题是,只要找到匹配项,您的代码就会重新排列名为$good_domains
的数组,因此每次都会减少count($good_domains)
,但不会重置$y
值。
添加:
$y--;
在此之下:
$good_domains = array_values($good_domains);
答案 1 :(得分:1)
使用简单的foreach
循环,因为这样您就不必使用array_values()
函数。所以你的remove_excluded_domains()
功能应该是这样的:
function remove_excluded_domains($good_domains, $bad_domains) {
foreach($bad_domains as $bad_domain){
foreach($good_domains as $key => $good_domain){
if(strpos($good_domain, $bad_domain) !== false){
unset($good_domains[$key]);
}
}
}
return $good_domains;
}
$spider_array = remove_excluded_domains($good_domains, $bad_domains);
注意:如果您希望以数字方式对数组建立索引,请在返回的数组上使用array_values()
函数,如下所示:
$spider_array = array_values(remove_excluded_domains($good_domains, $bad_domains));