douling6469 2017-03-05 15:32
浏览 46
已采纳

按优先级php中的键值排序数组

i have a array with results. now i want to show the results in a grid in a sorted way. therefor i need to alter this array.

sort needs to be like this "order" - "pre-order" - "closed" but then i also have a "sort" value so i want to first sort on the 3 open status types and then within these types on the sort value, example array:

            $arr = [
            0 => ['id'=>1, 'sort'=>2, 'status'=>'closed', 'name'=>'some name...'],
            1 => ['id'=>2, 'sort'=>1, 'status'=>'closed', 'name'=>'some name...'],
            2 => ['id'=>3, 'sort'=>3, 'status'=>'open', 'name'=>'some name...'],
            3 => ['id'=>4, 'sort'=>5, 'status'=>'pre-order', 'name'=>'some name...'],
            4 => ['id'=>5, 'sort'=>4, 'status'=>'closed', 'name'=>'some name...'],
            5 => ['id'=>6, 'sort'=>6, 'status'=>'pre-order', 'name'=>'some name...'],
            6 => ['id'=>7, 'sort'=>7, 'status'=>'pre-order', 'name'=>'some name...'],
            7 => ['id'=>8, 'sort'=>9, 'status'=>'open', 'name'=>'some name...'],
            8 => ['id'=>9, 'sort'=>8, 'status'=>'open', 'name'=>'some name...'],
            9 => ['id'=>10, 'sort'=>10, 'status'=>'closed', 'name'=>'some name...'],
            10 => ['id'=>11, 'sort'=>11, 'status'=>'closed', 'name'=>'some name...'],
        ];

i dit it by several loops adding the types to a new array checking the open status, but i can not make it work with the sort.

  • 写回答

2条回答 默认 最新

  • drpogkqqi536984960 2017-03-05 16:22
    关注

    An other way using pack:

    $result = [];
    $status = ['open'=>1, 'pre-order'=>2, 'closed'=>3];
    foreach ($arr as $v) {
        $key = $status[$v['status']] . pack("n", $v['sort']);
        $result[$key] = $v;
    }
    ksort($result);
    $result = array_values($result);
    

    or without after all:

    $result = [];
    $status = ['open'=>1e5, 'pre-order'=>2e5, 'closed'=>3e5];
    foreach ($arr as &$v) {
        $key = $status[$v['status']] + $v['sort'];
        $result[$key] = $v;
    }
    ksort($result);
    $result = array_values($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来