php - 如何以这种方式按字母顺序排列域列表?

标签 php

因此,如果我想按字母顺序组织一个网站列表,并且所有网站都是这种形式:example1.com、test.com、stackoverflow.com、google.com,这很容易。但是,我还想组织子域。考虑以下三个域:

a.domain.com
domain.com
anotherdomain.com

如果我将它们交给软件按字母顺序排列,它们将按字母顺序排列如下:

a.domain.com
anotherdomain.com
domain.com

但是,这不是我希望它们按字母顺序排列的方式。我希望它们按域按字母顺序排列,然后按子域作为“决胜局”,换句话说,像这样:

anotherdomain.com
domain.com
a.domain.com

有人能告诉我如何编写 PHP(或 JavaScript)代码来执行此操作吗? (您可以假设每个“网站”都在新的代码行上。)

最佳答案

$array = array(
    'b.domain.com',
    'a.domain.com',
    'domain.com',
    'anotherdomain.com',
    'php.net',
    'example.com'
);

function sort_domains($domain1, $domain2)
{
    $domain1 = array_reverse(explode('.', $domain1));
    $domain2 = array_reverse(explode('.', $domain2));
    // set $i to 0 if you want the TLD to be sorted
    for($i = 1; ; $i++)
    {
        // Might be a good idea to store the value of the issets up here
        if(isset($domain1[$i]) && isset($domain2[$i]))
        {
            $difference = strcmp($domain1[$i], $domain2[$i]);
            if($difference != 0)
            {
                return $difference;
            }
            continue;
        }
        if(!isset($domain1[$i]) && !isset($domain2[$i]))
        {
            return 0;
        }
        return isset($domain1[$i]) ? 1 : -1;
    }
}

usort($array, 'sort_domains');

/*
Array
(
    [0] => anotherdomain.com
    [1] => domain.com
    [2] => a.domain.com
    [3] => b.domain.com
    [4] => example.com
    [5] => php.net
)
*/

编辑:

根据 Alnitak 的建议,这里是 sort_domains 的一个版本,它缓存了每个域名的片段:

function sort_domains($domain1, $domain2)
{
    static $cache = array();
    if(!array_key_exists($domain1, $cache))
    {
        $cache[$domain1] = array_reverse(explode('.', $domain1));
    }
    if(!array_key_exists($domain2, $cache))
    {
        $cache[$domain2] = array_reverse(explode('.', $domain2));
    }
    // set $i to 0 if you want the TLD to be sorted
    for($i = 1; ; $i++)
    {
        $isset_1 = isset($cache[$domain1][$i]);
        $isset_2 = isset($cache[$domain2][$i]);
        if($isset_1 && $isset_2)
        {
            $difference = strcmp($cache[$domain1][$i], $cache[$domain2][$i]);
            if($difference != 0)
            {
                return $difference;
            }
            continue;
        }
        if(!$isset_1 && !$isset_2)
        {
            return 0;
        }
        return $isset_1 ? 1 : -1;
    }
}

关于php - 如何以这种方式按字母顺序排列域列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5624394/

相关文章:

php - Swagger-php - 如何以编程方式添加路径?

javascript - Angular2 http.get 预检问题

php - ffprobe/ffmpeg exec 不在本地机器上返回结果,但在生产系统上工作

php - 使用下拉值返回PHP查询结果

php - 我如何使用 php 检索段落的匹配字符串

php - 找出创建类实例的目录?

php - 试图让论坛显示类别的所有子类别

php - 插入查询执行两次而不是一次

php - Laravel 4 中 Request::route() 的等价物是什么?

php - 根据特定数据计算用户的相关性