如果要修改输入数组,而不是生成新的过滤数组,可以使用strpos()标识url,lookup数组标识重复url,unset()修改数组。
-
strpos($v,'http')===0 不仅要求 http 在字符串中,还要求它是字符串中的前四个字符。需要明确的是,这也适用于https。在简单地检查子字符串的存在或位置时,strstr() 和 substr() 的效率总是低于strpos()。 (第二个注释 @PHP Manual's strstr() 夸耀在仅检查子字符串是否存在时使用 strpos() 的好处。)
- 使用迭代的
in_array() 调用来检查$lookup 数组的效率低于将重复的url 作为键存储在查找数组中。 isset() 每次都会胜过 in_array()。 (Reference Link)
- OP 的示例输入并未表明存在任何以
http 开头但不是url 的猴子值,也不是以http 开头的非url。因此,strpos() 是一个合适且轻量级的函数调用。如果麻烦的 url 是可能的,那么 sevavietl 的 url 验证是一个更可靠的函数调用。 (PHP Manual Link)
- 根据我的在线性能测试,我的答案是提供所需输出数组的最快方法。
代码:(Demo)
$array=[
'EM Debt'=>'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB',
'EM Local Debt'=>'Will be launched shortly',
'EM Blended Debt'=>'Will be launched shortly',
'Frontier Markets'=>'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262',
'Absolute Return Debt and FX'=>'Will be launched shortly',
'Em Debt'=>'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262'
];
foreach($array as $k=>$v){
if(isset($lookup[$v])){ // $v is a duplicate
unset($array[$k]); // remove it from $array
}elseif(strpos($v,'http')===0){ // $v is a url (because starts with http or https)
$lookup[$v]=''; // store $v in $lookup as a key to an empty string
}
}
var_export($array);
输出:
array (
'EM Debt' => 'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0616502026&culture=en-GB',
'EM Local Debt' => 'Will be launched shortly',
'EM Blended Debt' => 'Will be launched shortly',
'Frontier Markets' => 'http://globalevolution.gws.fcnws.com/fs_Overview.html?isin=LU0501220262',
'Absolute Return Debt and FX' => 'Will be launched shortly',
)
只是为了好玩,函数式/非正统/复杂的方法可能看起来像这样(不推荐,纯粹是演示):
var_export(
array_intersect_key(
$array, // use $array to preserve order
array_merge( // combine filtered urls and unfiltered non-urls
array_unique( // remove duplicates
array_filter($array,function($v){ // generate array of urls
return strpos($v,'http')===0;
})
),
array_filter($array,function($v){ // generate array of non-urls
return strpos($v,'http')!==0;
})
)
)
);