dou4624 2013-07-10 07:53
浏览 54
已采纳

PHP排序数组通过个性化订单

I need to sort an array, I've done this before but it has been easy because the array had numbers or letters to sort in ascedning/descending or alphabetical order.. In this case i have an array of which each element has 3 values, eg:

array[0]=code=1234
        =description='example array'
        =orderCode=P

array[1]=code=1235
        =description='example array1'
        =orderCode=A
.
.
.

Now i need to order theese reading the orderCode value in this order: P,I,B,C,A,S,D. The way i thought of getting arround it was to add another value to the array and to something like:

if($array[$c]['orderCode'] == 'P')
     $array[$c]['newOrderCode'] = 0;
if($array[$c]['orderCode'] == 'I')
     $array[$c]['newOrderCode'] = 1;
if($array[$c]['orderCode'] == 'B')
     $array[$c]['newOrderCode'] = 2;

or a switch case and then order it by the new value. This would work, but my question is, is there a function I can pass the array to and an orderring string or something?

Thank you, James

  • 写回答

2条回答 默认 最新

  • doulv8162 2013-07-10 07:56
    关注

    In php 5.3 and above you can use usort with a closure.

    $order = array('P','I','B','C','A','S','D');
    usort($array, function ($a, $b) use ($order){
         return array_search($a["orderCode"], $order) - array_search($b["orderCode"], $order);
    });
    

    prior to that you have to create a sorter function

    function orderCode_sorter($a, $b){
        $order = array('P','I','B','C','A','S','D');
        return array_search($a["orderCode"], $order) - array_search($b["orderCode"], $order);
    }
    usort($array, "orderCode_sorter");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线