How to sort a multidimensional array using a specific key?

It should be really simple, but what is the way to do it. I want to sort a multidimensional array using a key, for example:

Array ( [0] => Array ( [iid] => 1 [invitee] => 174 [nid] => 324343 [showtime] => 2010-05-09 15:15:00 [location] => 13 [status] => 1 [created] => 2010-05-09 15:05:00 [updated] => 2010-05-09 16:24:00 ) [1] => Array ( [iid] => 1 [invitee] => 220 [nid] => 21232 [showtime] => 2010-05-09 15:15:00 [location] => 12 [status] => 0 [created] => 2010-05-10 18:11:00 [updated] => 2010-05-10 18:11:00 )) 

Say I want to sort this by status, how would I achieve this? Thanks in advance!

+4
source share
5 answers
 //define a comparison function function cmp($a, $b) { if ($a['status'] == $b['status']) { return 0; } return ($a['status'] < $b['status']) ? -1 : 1; } usort($array, "cmp"); 

This should do what you want, you can change the comparison function to sort by any key you want.

+6
source

Try this: Using array_multisort

 $sort = array(); foreach($your_array as $k=>$v) { $sort['status'][$k] = $v['status']; } array_multisort($sort['status'], SORT_DESC, $your_array); echo "<pre>"; print_r($your_array); 

Link: http://php.net/manual/en/function.array-multisort.php

+2
source

The usort function is what you are looking for:

 <?php function cmp($a, $b) { return $b["status"] - $a["status"]; } $sorted = usort($your_array, "cmp"); var_dump($sorted); ?> 
+1
source

try it

 function cmp_by_status($a, $b) { if ($a['status'] == $b['status']) { return 0; } return ($a['status'] < $b['status') ? -1 : 1; } usort($data_array, "cmp_by_status"); 
0
source

I added this answer to Sort a multidimensional array by a specific key, sorts a specific array key to sort the array value.

 function sortBy($field, &$array, $direction = 'asc') { usort($array, create_function('$a, $b', ' $a = $a["' . $field . '"]; $b = $b["' . $field . '"]; if ($a == $b) { return 0; } return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1; ')); return true; } 

Call this function using a specific array key

 sortBy('status', $array); 
0
source

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


All Articles