How to sort php array alphabetically after a specific character in a string

I have two php arrays. And you have another sort question for each of these arrays:

1) First contains a list of domains:

values[0] = "absd.com";
values[1] = "bfhgj.org";
values[2] = "sdfgh.net";
values[3] = "sdff.com";
values[4] = "jkuyh.ca";

I need to sort this array alphabetically by DOMAIN value, in other words, by value after ".", So the sorted domain will look like this:

values[0] = "jkuyh.ca";
values[1] = "absd.com";
values[2] = "sdff.com";
values[3] = "sdfgh.net";
values[4] = "bfhgj.org";

2) I also have a second array that contains "double" domain values:

values[0] = "lkjhg.org.au";
values[1] = "bfhgj.co.uk";
values[2] = "sdfgh.org.uk";

I need to sort this array alphabetically using the value DOUBLE DOMAIN, in other words, the value after the first instance of '.' in the domain, so the sorted domain will look like this:

values[1] = "bfhgj.co.uk";
values[0] = "lkjhg.org.au";
values[2] = "sdfgh.org.uk";

How do I solve this problem? The approach is sort()sorted based on the first letter only ...

+3
2

:

usort ($values,
    function ($a,$b) {
       return strcmp (strstr ($a, '.'), strstr ($b, '.'));
    });

, , "."

, , , , :

$values = array ("zercggj.co.uk", "lkjhg.org.au", "qqxze.org.au",
                 "bfhgj.co.uk", "sdfgh.org.uk");

echo "<br>input:<br>";
foreach ($values as $host) echo "$host<br>";

// create a suitable structure
foreach ($values as $host)
{
    $split = explode('.', $host, 2);
    $printable[$split[1]][] = $split[0];
}

// sort by domains
asort ($printable);

// output
echo "<br>sorted:<br>";
foreach ($printable as $domain => $hosts)
{
    echo "domain: $domain<br>";

    // sort hosts within the current domain
    asort ($hosts);

    // display them
    foreach ($hosts as $host)
        echo "--- $host<br>";
}

, , , , (, ).

+2

usort .

:

usort($values,function($a,$b) {
    return strcasecmp(
        explode(".",$a,2)[1],
        explode(".",$b,2)[1]
    );
});

( , explode , PHP 5.3 )

+6

All Articles