簡體   English   中英

如何按字母數字值對多維數組進行排序?

[英]How to sort a multidimensional array by alphanumeric value?

我有一個像下面這樣的數組,

Array
(
    [2] => Array
        (
            [id] => 75
            [program] => Apr 2020-Nov 2020
        )

    [1] => Array
        (
            [id] => 73
            [program] => Feb 2016-Aug 2020
        )

    [0] => Array
        (
            [id] => 72
            [program] => May 2020-Dec 2020
        )

)

結果數組應該是

Array
(


    [1] => Array
        (
            [id] => 73
            [current_program] => Feb 2016-Aug 2020
        )
    [2] => Array
        (
            [id] => 75
            [current_program] => Apr 2020-Nov 2020
        )

    [0] => Array
        (
            [id] => 72
            [current_program] => May 2020-Dec 2020
        )

)

它應該根據年份排序。 我試圖通過“strnatcasecmp”來實現,但數組是按字母排序的,而不是按其中的數值排序

    usort($programp, function($a, $b) {
        return strnatcasecmp($a['program'], $b['program']);
    });

任何幫助,將不勝感激!

謝謝

您需要將第一個月和第一年轉換為時間戳,對其進行排序,從而對原始進行排序:

foreach($programp as $values) {
    $starts[] = strtotime(explode('-', $values['program'])[0]);
} 
array_multisort($starts, $programp);

在排序之前$starts數組看起來像這樣,很容易排序:

Array
(
    [0] => 1585692000
    [1] => 1454281200
    [2] => 1588284000
)

您可能需要一些錯誤檢查以確保$values['program']不為空等...

//Sort indexes so the keys are 0,1,2 instead of 1,2,0
//This is important when sorting down below with asort()
$arr = array_values($arr); 

//Go through every "program" (dateinterval in your array)
//and make a new array in the format year-monthnr
//Date parse returns the number of jan(1),feb(2),mar(3) etc..
$year_month = [];
foreach(array_column($arr,'program') as $key => $item) {       
    $year = explode(' ', explode('-',$item)[0])[1];
    $month = date_parse(explode(' ', explode('-',$item)[0])[0])['month'];
    $year_month[] = $year . '-' . $month;
}

//Sort with mainted indexes (keys)
asort($year_month); 

//Create new array "mapped" keys to the original array $arr
$new_arr = [];
foreach($year_month as $key=>$item) {
    $new_arr[] = $arr[$key];
}

$new_arr將是:

Array
(
    [0] => Array
        (
            [id] => 73
            [program] => Feb 2016-Aug 2020
        )

    [1] => Array
        (
            [id] => 75
            [program] => Apr 2020-Nov 2020
        )

    [2] => Array
        (
            [id] => 72
            [program] => May 2020-Dec 2020
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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