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

时间:2017-03-05 15:32:03

标签: php arrays sorting

我有一个包含结果的数组。现在我想以排序的方式在网格中显示结果。因此我需要改变这个阵列。

排序需要像这样的“订单” - “预购” - “关闭” 但是我还有一个“排序”值,所以我想首先对3种打开的状态类型进行排序,然后在排序值的这些类型中排序,示例数组:

            $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...'],
        ];

我通过几个循环将它添加到一个新数组中来检查打开状态,但是我无法使其与排序一起工作。

2 个答案:

答案 0 :(得分:1)

您可以使用usort执行此操作

$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...'],
];

usort($arr, function($a, $b) {
    if ($a['status'] == $b['status']) return $b['sort'] - $a['sort'];
    else {
        if ($a['status'] == "open") return -1;
        else if ($b['status'] == "open") return 1;
        else if ($a['status'] == "pre-order")  return -1;
        else return 1;
    }
});

var_dump($arr);

答案 1 :(得分:0)

使用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);

或者毕竟没有:

$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);