首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将URL数组限制为最大值。每个subdomain+domain 3个项目

将URL数组限制为最大值。每个subdomain+domain 3个项目
EN

Stack Overflow用户
提问于 2020-05-07 17:29:51
回答 1查看 27关注 0票数 0

我有这个数组:

代码语言:javascript
复制
$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个项目?

这会给我

代码语言:javascript
复制
$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'
);

感谢您的帮助!

EN

回答 1

Stack Overflow用户

发布于 2020-05-07 17:37:03

使用parse_url解析每个项目的域,并维护一个数组来跟踪每个域的频率。

代码语言:javascript
复制
$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;
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61654380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档