php 多維陣列的排序實現代碼

來源:互聯網
上載者:User

如數組

 代碼如下 複製代碼

Array
(
   [0] => Array
       (
           [id] => 1146
           [orderid] => 3
       )

   [1] => Array
       (
           [id] => 1149
           [orderid] => 2
       )

   [2] => Array
       (
           [id] => 170
           [orderid] => 4
       )

   [3] => Array
       (
           [id] => 1121
           [orderid] => 3
       )

   [4] => Array
       (
           [id] => 1120
           [orderid] => 7
       )

)

這麼一個資料,想按orderid來排序。找不到內建的php函數,網上搜尋了下,發現如下方法:

 代碼如下 複製代碼


$asc_func  =  create_function('$a,$b',' 
$k  =  "orderid";
if($a[$k]  ==  $b[$k])  return  0; 
return  $a[$k]>$b[$k]?1:-1; 
'); 
usort($arrs,$asc_func); 

$arrs是原數組,$k="orderid"是要排序的欄位

後來對上面代碼進行了升級

 代碼如下 複製代碼

function sysSortArray($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }

    // Get args number.
    $ArgCount = func_num_args();

    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I < $ArgCount;$I ++)
    {
        $Arg = func_get_arg($I);
        if(!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }

    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }

    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.