php按IP地址排序网址

时间:2012-06-26 22:16:06

标签: php

好的,我在一个不太清楚的问题之前发布了,所以让我再试一次。 我试图将我的网站组织成每批5个站点,每个站点都有不同的IP地址。

为此,我必须为每个网址即时获取IP,然后将这些网站组织成每批5个网站,每个网站都有自己唯一的IP地址。

如果我有多个IP地址,则必须在下一批中显示。

任何人都可以帮我解决这个问题吗?

我有一个包含网站的数组,并且有IP。

这是我的代码:

if(isset($Organize_List)){
 $List =   explode("\n", $Organize_List);
$IP_Array = array();
      foreach($List as $SIte){
    $Ip = gethostbyname(trim($SIte));
      if(preg_match('/^\d+$/', $Ip[1])){
         $IP_Array[$Ip][] = $SIte.'<br />';
                }
 }

现在这里变得棘手。

我的问题是如何将它们组织成每批5个网站的批次,每个网站都有自己独特的IP地址。

1 个答案:

答案 0 :(得分:0)

/* your base data */
$domains = array(/* your data */);

/* a list of domains per ip number, like $domain_by_ip['64.34.119.12'] = 'stackoverflow.com' */
$domain_by_ip = array();

/* a list counting number of domains by ip number */
$ip_count = array();

/* a list of domains we faild to fetch ip number for */
$failed = array();

/* loop through all doains */
foreach($domains as $current_domain)
{
   /* fetch the A record for all domains */
   $current_dns_record = dns_get_record($current_domain, DNS_A);

   /* if there is a dns record */
   if($current_dns_record)
   {
      /* fetch ip from result */
      $current_ip = $current_dns_record[0]['ip'];

      /* thos row is not needed, but php may triggering a warning oterhwise */
      if(!isset($domain_by_ip[$current_ip])) $domain_by_ip[$current_ip] = array();
      if(!isset$ip_count[$current_ip])) $ip_count[$current_ip] = array();

      /* add domain to the list by ip */
      $domain_by_ip[$current_ip][] = $current_dns_record;

      /* count up the count of domains on this ip */
      $ip_count[$current_ip]++;
   }
   else
   {
      /* if there was no dns record, put this domain on the fail list */
      $failed[] = $current_domain;
   }
}

/* create a list for storing batches */
$batches = array();

/* as long as we have ip-numbers left to use */
while($ip_count)
{
   /* create a list for storing current batch */
   $current_batch = array();

   /* sort ip-numbers so we take the ip-numbers whit most domains first */
   arsort($ip_count);

   /* take the top 5 ip-numbers from the list */
   $current_batch_ip_list = array_slice(array_keys($ip_count), 0, 5);

   /* foreach of thous 5 ip-numbers .. */
   foreach($current_batch_ip_list as $current_ip)
   {
      /* move one domain from the domain by ip list to the current batch */
      $current_batch[] = array_pop($domain_by_ip[$current_ip]);

      /* count down the numbers of domains left for that ip */
      $ip_count[$current_ip]--;

      /* if there is no more domains on this ip, remove it from the list */
      if($ip_count[$current_ip] == 0)
      {
         unset($ip_count[$current_ip]);
      }
   }

   /* add current batch to the list of batches */
   $batches[] = $current_batch;
}