Смешанные домены Как навести определенный порядок? - PullRequest
0 голосов
/ 25 сентября 2019

СЛУЧАЙНЫЙ СПИСОК ДОМЕНОВ:

$DOMAIN_ARRAY = [
    'mydomain.com',
    'hair.mydomain.com',
    'web.developer.yoursite.com',
    'game.yoursite.com',
    'yoursite.com',
    'good.mydomain.com',
    'great.yoursite.com',
    'test.page.mydomain.com',
    'check.yoursite.com',
    'test.mydomain.com'
];

ЖЕЛАЕМЫЙ РЕЗУЛЬТАТ:

mydomain.com

  • test.page.mydomain.com

  • hair.mydomain.com

  • good.mydomain.com

  • test.mydomain.com

yoursite.com

  • web.developer.yoursite.com

  • game.yoursite.com

  • great.yoursite.com

  • check.yoursite.com

      <?php       
      $URL = "ide.geeksforgeeks.org";    
     $arr = preg_split('[\.]', $URL);     
     $subdomain = $arr[0];      
     echo $subdomain;
    

1 Ответ

0 голосов
/ 25 сентября 2019
<?php

$domains = [
    'mydomain.com',
    'hair.mydomain.com',
    'web.developer.yoursite.com',
    'game.yoursite.com',
    'yoursite.com',
    'good.mydomain.com',
    'great.yoursite.com',
    'test.page.mydomain.com',
    'check.yoursite.com',
    'test.mydomain.com'
];

function domainsFirst($a, $b)
{   
    if ($a == $b) {
      return 0;
    }
    return (substr_count($a, '.') < substr_count($b, '.')) ? -1 : 1;
}

// Sorts the array by main domains first
usort($domains, "domainsFirst");

$result = [];

foreach ($domains as $domain){
    // Main domain
    if (substr_count($domain, '.') == 1){
        if (!isset($result[$domain])){
            $result[$domain] = [];
        }
    } else { // Subdomain
        $sub = explode('.', $domain);
        // Discover the main domain by taking the two last indexes
        $key = $sub[count($sub) - 2]. '.' .$sub[count($sub) - 1];
        $result[$key][] = $domain;
    }
}

print_r($result);

Выходы

Array
(
    [yoursite.com] => Array
        (
            [0] => check.yoursite.com
            [1] => great.yoursite.com
            [2] => game.yoursite.com
            [3] => web.developer.yoursite.com
        )

    [mydomain.com] => Array
        (
            [0] => test.mydomain.com
            [1] => good.mydomain.com
            [2] => hair.mydomain.com
            [3] => test.page.mydomain.com
        )

)

https://3v4l.org/tK9Kk

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...