PHP double substring-based sorting array

I am creating a custom switch manager to work, my current problem is more aesthetically pleasing, but I think it is a good learning experience. For clarity, I placed the array below:

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 large switches, I use asort($arr); to get GigabitEthernet1 / 1 to 2/1, etc.

My goal is to sort by interface number (the part after '/') so that 1/8 falls to 1/10.

Can someone point me in the right direction, I want to work for the results, but I'm not familiar enough with PHP to know exactly where to go.

Notes. When using larger multi-module switches, the identifiers are not ordered, so sorting by $ arr [key] will not work.

+6
source share
2 answers

You can use the flag when using asort () as shown below.

 asort($arr, SORT_NATURAL | SORT_FLAG_CASE);print_r($arr); 

It will print / sort the data as you need.

+6
source

SORT_NATURAL and SORT_FLAG_CASE require v5.4 +.

If you are using an older version of PHP, you can do this with uasort and a special comparison callback function.

 $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); 
+2
source

Source: https://habr.com/ru/post/951477/


All Articles