[英]PHP double sort array based on substring
I am building a custom switch manager for work, my current issue is more an aesthetic one but I think it is a good learning experience. 我正在为工作建立一个自定义交换机管理器,我目前的问题更美观,但我认为这是一个很好的学习经验。 I have posted the array below for clarity:
为了清楚起见,我在下面发布了数组:
Array
(
[1] => FastEthernet0/1
[10] => FastEthernet0/10
[11] => FastEthernet0/11
[12] => FastEthernet0/12
[13] => FastEthernet0/13
[14] => FastEthernet0/14
[15] => FastEthernet0/15
[16] => FastEthernet0/16
[17] => FastEthernet0/17
[18] => FastEthernet0/18
[19] => FastEthernet0/19
[2] => FastEthernet0/2
[20] => FastEthernet0/20
[21] => FastEthernet0/21
[22] => FastEthernet0/22
[23] => FastEthernet0/23
[24] => FastEthernet0/24
[3] => FastEthernet0/3
[4] => FastEthernet0/4
[5] => FastEthernet0/5
[6] => FastEthernet0/6
[7] => FastEthernet0/7
[8] => FastEthernet0/8
[9] => FastEthernet0/9
[25] => Null0
)
On our bigger switches I am using asort($arr);
在我们更大的交换机上,我使用的是
asort($arr);
to get GigabitEthernet1/1 to come before 2/1, etc... 在2/1之前获得GigabitEthernet1 / 1等...
My goal is to sort on the interface number (part after '/') so that 1/8 comes before 1/10. 我的目标是对接口号进行排序(在'/'之后的部分),以便1/8在1/10之前。
Could someone point me in the right direction, I want to work for the results but I am not familiar enough with PHP to know exactly where to go. 有人能指出我正确的方向,我想为结果工作,但我不熟悉PHP知道到底要去哪里。
Notes: On out larger multi-module switches the IDs are not in order so a sort on $arr[key] won't work. 注意:在较大的多模块交换机上,ID不是有序的,因此对$ arr [key]的排序将不起作用。
You can use the flag while using asort(), like below. 您可以在使用asort()时使用该标志,如下所示。
asort($arr, SORT_NATURAL | SORT_FLAG_CASE);print_r($arr);
It will print/sort the data as yo need. 它将根据您的需要打印/排序数据。
The SORT_NATURAL and SORT_FLAG_CASE requires v5.4+. SORT_NATURAL和SORT_FLAG_CASE需要v5.4 +。
If you're using an older version of PHP, you could do it with uasort and a custom comparison callback function. 如果您使用的是旧版本的PHP,则可以使用uasort和自定义比较回调函数来完成。
$interfaces = array(...);
$ifmaj = array();
$ifmin = array();
$if_cmp = function ($a, $b) {
list($amaj,$amin) = split('/',$a);
list($bmaj,$bmin) = split('/',$b);
$maj = strcmp($amaj,$bmaj);
if ($maj!=0) return $maj;
//Assuming right side is an int
return $amin-$bmin;
};
uasort($interfaces, $if_cmp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.