Home > Software engineering >  How to sort emails by its extension and put them to same line
How to sort emails by its extension and put them to same line

Time:06-11

I have a list of emails like bellow:

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

I want to sort them by extension then put email with same extension to same line:

[email protected]|[email protected]
[email protected]|[email protected]|[email protected]
[email protected]

My idea is reverse eachline using foreach() and strrev() then sort(), but I don't know how to put email with same extension to same line:

foreach($emailLines as $eachLine){
    $revArr[$i  ] = strrev($eachLine);
}
sort($revArr);

Please help me, thanks.

CodePudding user response:

Try this

<?php
$emails = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
];
$emailSort = [];
foreach ($emails as $email) {
    $parts = explode('@', $email);
    $emailSort[$parts[1]][] = $email;
}
ksort($emailSort);
$emailStrings = [];
foreach ($emailSort as $value) {
    asort($value);
    $emailStrings[] = implode('|', $value);
}
var_dump($emailStrings);
  • Related