Search code examples
phparrayscisco

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); to get GigabitEthernet1/1 to come before 2/1, etc...

My goal is to sort on the interface number (part after '/') so that 1/8 comes before 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.

Notes: On out larger multi-module switches the IDs are not in order so a sort on $arr[key] won't work.


Solution

  • You can use the flag while using asort(), like below.

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

    It will print/sort the data as yo need.