因此,如果我想按字母顺序组织一个网站列表,并且有以下所有形式:example1.com,test.com,stackoverflow.com,google.com,那将很容易.但是,我还要组织子域.考虑以下三个域:
a.domain.com
domain.com
anotherdomain.com
Run Code Online (Sandbox Code Playgroud)
如果我将它们交给软件进行字母顺序排列,它们将按字母顺序排列如下:
a.domain.com
anotherdomain.com
domain.com
Run Code Online (Sandbox Code Playgroud)
但是,这不是我希望它们按字母顺序排列的方式.我希望它们按域按字母顺序排列,然后通过子域作为"决胜局",换句话说,就像这样:
anotherdomain.com
domain.com
a.domain.com
Run Code Online (Sandbox Code Playgroud)
有人能告诉我如何编写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
)
*/
Run Code Online (Sandbox Code Playgroud)
编辑:
根据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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |