因此,如果我想按字母顺序组织一个网站列表,并且所有网站都是这种形式: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/