PHP:根据值列表排序多维数组

时间:2016-04-01 09:10:46

标签: php arrays

鉴于此数组:

Array
(
    [0] => Array
        (
            [status] => closed
            [userModifiedAt] => 2015-12-09T11:47:46Z
        )

    [1] => Array
        (
            [status] => active
            [userModifiedAt] => 2016-02-08T16:43:26Z
        )

    [2] => Array
        (
            [status] => closed
            [userModifiedAt] => 2016-03-31T03:47:19Z
        )

    [3] => Array
        (
            [status] => pending
            [userModifiedAt] => 2015-12-08T14:09:58Z
        )

我想通过此订单按[status]订购: - 等待 - 活跃 - 关闭

对于每种状态,请按[userModifiedAt]订购。

我正在使用此代码:

usort($array, function($a,$b){ return strcmp($a['status'], $b['status']);} );

但它按字母顺序排列,因此状态排序为: - 活跃 - 关闭 - 待定

如何根据预定义的订单列表订购数组?

1 个答案:

答案 0 :(得分:7)

这将是一个技巧 -

$array  =   array(
    1 => array(
      "id"=>1,
      "name"=>"Test #1",
      "listorder"=>1
    ),
    6   =>  array(
        "id"=>6,
        "name"=>"Test #1",
        "listorder"=>3
    ),  
    2   =>  array(
        "id"=>2,
        "name"=>"Test #2",
        "listorder"=>2
    )   
);


function sort_count($a, $b) {
    if ($a['listorder'] === $b['listorder']) {
      return 0;
    } else {
       return ($a['listorder'] > $b['listorder'] ? 1:-1);
    }
}

$sorted_array = uasort($array, 'sort_count');

echo "<pre>";
print_r($array);
echo "</pre>";

<强>输出

## A array with the orders to be considered
$order = array('active' => 1, 'closed' => 2, 'pending' => 3);

usort($array, function($a, $b) use($order) { // Use the order array to compare
    return $order[$a[status]] - $order[$b[status]];
});

var_dump($array);

如果您需要不同的订单,请更改订单array(4) { [0]=> array(2) { ["status"]=> string(6) "active" ["userModifiedAt"]=> string(20) "2016-02-08T16:43:26Z" } [1]=> array(2) { ["status"]=> string(6) "closed" ["userModifiedAt"]=> string(20) "2015-12-09T11:47:46Z" } [2]=> array(2) { ["status"]=> string(6) "closed" ["userModifiedAt"]=> string(20) "2016-03-31T03:47:19Z" } [3]=> array(2) { ["status"]=> string(7) "pending" ["userModifiedAt"]=> string(20) "2015-12-08T14:09:58Z" } } 。具有最低值的键将首先在array上。如果您想首先关闭,请在array数组中为其提供最低值。

DEMO