我有这个数组:
$links = array(
'http://www.youtube.com/1',
'https://www.youtube.com/2',
'http://www.youtube.com/3',
'http://www.youtube.com/4',
'http://music.youtube.com/1',
'https://music.youtube.com/2',
'https://music.youtube.com/3',
'http://music.youtube.com/4',
'http://www.amazon.com/1',
'http://www.another.com/1'
);如何对其进行过滤,使每个subdomain+domain最多只保留3个项目?
这会给我
$new_links = array(
'http://www.youtube.com/1',
'https://www.youtube.com/2',
'http://www.youtube.com/3',
'http://music.youtube.com/1',
'https://music.youtube.com/2',
'https://music.youtube.com/3',
'http://www.amazon.com/1',
'http://www.another.com/1'
);感谢您的帮助!
发布于 2020-05-07 17:37:03
使用parse_url解析每个项目的域,并维护一个数组来跟踪每个域的频率。
$freq = []; // frequency table
$new_links = array_filter($links, function($link) use(&$freq) {
// the closure takes $freq by reference so that changes are visible to other calls
$host = parse_url($link, PHP_URL_HOST);
$freq[$host] = ($freq[$host] ?? 0) + 1; // increment, or set to 1 if not exists
// $freq[$host] is the number of times this domain has appeared, including the current one
return $freq[$host] > 3;
});https://stackoverflow.com/questions/61654380
复制相似问题