Reputation: 649
This function works perfectly to sort a list alphabetically and clean all doubles.
function cleanMyList($myFile)
{
$myTextFile=file_get_contents($myFile);
$myArray=explode("\r\n",$myTextFile);
$myArray=array_unique($myArray);
sort($myArray);
$myTextFile=implode("\r\n",$myArray);
return $myTextFile;
}
echo '<pre>'.cleanMyList('emails.txt').'</pre>';
exit;
This script works just fine but now what I want to do is sort it again by email provider (in other words: by domain) so the list would be sorted twice, First alphabetically and then resort it by email provider.
Here is an example:
emails.txt (before):
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
email.txt after:
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
but I'm expecting to go one step further and get this (sort by domain) :
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Upvotes: 2
Views: 1738
Reputation: 59691
This should work for you:
I just changed your code a little bit. First I grab your file with file()
where I get ever line as an element in an array where I only take unique values with array_unique()
. After this I sort your array with usort()
where I check if the domain is the same and if yes then I sort it by the alphabet.
<?php
function cleanMyList($myFile) {
$myArray = array_unique(file($myFile, FILE_IGNORE_NEW_LINES));
usort($myArray, function($a, $b){
preg_match_all("/(.*)@(.*)\./", $a, $m1);
preg_match_all("/(.*)@(.*)\./", $b, $m2);
if(($cmp = strcmp($m1[2][0], $m2[2][0])) == 0) {
return strcmp($m1[1][0], $m2[1][0]);
} else {
return ($cmp < 0 ? -1 : 1);
}
});
return $myTextFile = implode(PHP_EOL, $myArray);
}
echo "<pre>" . cleanMyList('emails.txt') . "</pre>";
?>
Output:
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Upvotes: 2
Reputation: 606
$em="[email protected],[email protected], [email protected],[email protected]"; Split the emails in two part
$ar=split(",",$em);
while (list ($key, $val) = each ($ar)) {
$ar2=split("@",$val);
echo $ar2[0];
echo "<br>";
echo $ar2[1];
echo "<br><br>";
}
Sort Array (Ascending Order), According to Value - asort()
<?php
asort($ar2);
?>
Upvotes: 0