usort() 用户自定义排序的实现

  • Post author:
  • Post category:其他



usort() 用户自定义排序的实现



  1. function


    multi_compare(


    $a


    ,


    $b


    )


  2. {


  3. $criteria


    =


    array


    (



  4. ‘gold’


    =>


    ‘desc’


    ,



  5. ‘ts’


    =>


    ‘desc’




    //这里还可以根据需要继续加条件 如:’x’=>’asc’等




  6. );


  7. foreach


    (


    $criteria




    as




    $what


    =>


    $order


    ){



  8. if


    (


    $a


    [


    $what


    ] ==


    $b


    [


    $what


    ]){



  9. continue


    ;


  10. }


  11. return


    ((


    $order


    ==


    ‘desc’


    )?-1:1) * ((


    $a


    [


    $what


    ] <


    $b


    [


    $what


    ]) ? -1 : 1);


  12. }


  13. return


    0;


  14. }



  1. usort(


    $sorted_array


    ,


    “multi_compare”


    );