簡體   English   中英

基於子字符串的PHP雙排序數組

[英]PHP double sort array based on substring

我正在為工作建立一個自定義交換機管理器,我目前的問題更美觀,但我認為這是一個很好的學習經驗。 為了清楚起見,我在下面發布了數組:

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
)

在我們更大的交換機上,我使用的是asort($arr); 在2/1之前獲得GigabitEthernet1 / 1等...

我的目標是對接口號進行排序(在'/'之后的部分),以便1/8在1/10之前。

有人能指出我正確的方向,我想為結果工作,但我不熟悉PHP知道到底要去哪里。

注意:在較大的多模塊交換機上,ID不是有序的,因此對$ arr [key]的排序將不起作用。

您可以在使用asort()時使用該標志,如下所示。

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

它將根據您的需要打印/排序數據。

SORT_NATURAL和SORT_FLAG_CASE需要v5.4 +。

如果您使用的是舊版本的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM