I have this array
Array ( [data] => Array ( [0] => Array ( [id] => 1293005125 [viewed] => TRUE [active] => TRUE [time] => December 22, 2010 13:00 hours [timestamp] => 1293006034 [initial_timestamp] => 1293005125 [user] => administrator ) [1] => Array ( [mid] => 1293001908 [viewed] => TRUE [active] => TRUE [time] => December 22, 2010 13:00 hours [timestamp] => 1293001908 [initial_timestamp] => 1293001908 [user] => administrator ) [2] => Array ( [mid] => 1293009999 [viewed] => TRUE [active] => TRUE [time] => December 22, 2010 13:00 hours [timestamp] => 1293009999 [initial_timestamp] => 1293009999 [user] => administrator ) [3] => Array ( [mid] => 1293006666 [viewed] => TRUE [active] => TRUE [time] => December 22, 2010 13:00 hours [timestamp] => 1293006666 [initial_timestamp] => 1293006666 [user] => administrator ) [4] => Array ( [mid] => 1293005125 [viewed] => TRUE [active] => TRUE [time] => December 22, 2010 13:00 hours [timestamp] => 1293006125 [initial_timestamp] => 1293005125 [user] => administrator2 ) )
Now I would like to sort this array by [mid]
How do I do this?
Currently I sort this in a foreach loop
There has to be a better way
EDIT I hoped to output something like
[mid] key => array value
Thanks
The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.
A user-defined function can help in getting unique values from multidimensional arrays without considering the keys. You can use the PHP array unique function along with the other array functions to get unique values from a multidimensional array while preserving the keys.
The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.
You can use the usort function.
function cmp($a, $b) { return $a["mid"] - $b["mid"]; } usort($arr, "cmp");
See it
The other solution is using array_multisort
<?php // Obtain a list of columns foreach ($data as $key => $row) { $mid[$key] = $row['mid']; } // Sort the data with mid descending // Add $data as the last parameter, to sort by the common key array_multisort($mid, SORT_DESC, $data); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With