php - How do I alphabetize a list of domains in this way? -
so if wanted organize list of websites alphabetically, , there of form: example1.com, test.com, stackoverflow.com, google.com, easy. however, want organize subdomains. consider following 3 domains:
a.domain.com domain.com anotherdomain.com if handed them on software alphabetize, alphabetized this:
a.domain.com anotherdomain.com domain.com however, not how want them alphabetized. want them alphabetized domain, , subdomain "tiebreaker," in other words, this:
anotherdomain.com domain.com a.domain.com could tell me how code php (or javascript) this? (you can assume each "website" on fresh line of code.)
$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 0 if want tld sorted for($i = 1; ; $i++) { // might idea store value of issets 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 ) */ edit:
as per suggestion of alnitak, here version of sort_domains caches pieces of each domain name:
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 0 if want tld 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; } }
Comments
Post a Comment