PHP: arrange multidimensional array according to list of values

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 would like to order it by [status] using this order: - pending - active - closed

And for each state, the order is [userModifiedAt].

I am using this code:

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

But it works in alphabetical order, so the status is ordered as: - active - closed - pending

How can I arrange the array according to a predefined list of orders?

+5
source share
1 answer

It will 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 of the array if you need a different order. The key with the smallest value will first be on array . If you want the closed one to be the first, specify the minimum value in the $order array.

Demo

+7
source

Source: https://habr.com/ru/post/1246220/


All Articles