Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: order a multi-dimensional array according to a list of values [duplicate]

Tags:

arrays

php

Given this array:

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
        )

I'd like to order it by [status] with this order: - pending - active - closed

And for each status, order by [userModifiedAt].

I'm using this code:

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

But it works alphabetically, so the status is ordered as: - active - closed - pending

How can I order an array according to a predefined order list?

like image 650
Daniele B Avatar asked Apr 01 '16 09:04

Daniele B


1 Answers

This would be a trick -

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

Output

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"
  }
}

Change the order array if you want different order. Key with lowest value will be first on the array. If you want closed to be first then provide the lowest value to it in $order array.

DEMO

like image 176
Sougata Bose Avatar answered Nov 03 '22 04:11

Sougata Bose