如何在字符串中某个字符后按字母顺序对php数组进行排序 [英] How to alphabetically sort a php array after a certain character in a string

查看:158
本文介绍了如何在字符串中某个字符后按字母顺序对php数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个php数组。并对每个数组有一个不同的排序问题:

I have two php arrays. And have a different sorting question for each of these arrays:

1)首先包含域列表:

1) First contains list of domains:

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

我需要按DOMAIN值(即'后的值)按字母顺序对数组进行排序。 ',因此排序后的域如下:

I need to sort this array alphabetically by DOMAIN value, in other words by the value after the '.', so the sorted domain will be as follows:

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

2)我还有第二个包含双域值的数组:

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

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

我需要将此数组按DOUBLE DOMAIN值的字母顺序排序,换句话说,按第一个值后的值排序域中。的实例,因此排序后的域如下:

I need to sort this array alphabetically by DOUBLE DOMAIN value, in other words by the value after the first instance of '.' in domain, so the sorted domain will be as follows:

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

如何解决此问题? sort()方法仅根据首字母排序...

How do I tackle this issue? sort() approach sorts only based on first letter...

推荐答案

另一个变体:

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

这对您的两个数组都适用,因为比较使用的是从第一个字符串开始的部分'。

this will work for both your arrays, since the comparison uses the part of the string starting at the first '.'

如果您想按组将它们打印出来,我认为一个好的解决方案是首先创建一个合适的数据结构,然后将其用于排序和印刷:

If you want to print them out by groups, I think a good solution would be to first create a suitable data structure and then use it both for sorting and printing:

$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>";
}

这很好地说明了如何从考虑自己的想法中受益对整个数据进行处理,而不是专注于未连接的子任务(例如在这种情况下进行排序)。

This is a good illustration of how you can benefit from thinking about what you will do with your data as a whole instead on focussing on unconnected sub-tasks (like sorting in that case).

这篇关于如何在字符串中某个字符后按字母顺序对php数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆