通过子值sortingphpmultidimensional 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 ) ) 

现在我想按[mid]sorting这个数组,我该如何做?

目前我在foreach循环中sorting
必须有更好的方法

编辑我希望能输出类似的东西

[mid] key => array value

谢谢

您可以使用usortfunction。

 function cmp($a, $b) { return $a["mid"] - $b["mid"]; } usort($arr, "cmp"); 

看见

另一种解决scheme是使用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); ?> 

更新

我最近在“multidimensional arraysorting”的“确定性”主题中以更有效的方式回答了这个问题。 下面的答案针对老版本的PHP(5.2及更早版本); 虽然概念是健全的,但现在有更好的办法。 请阅读有关其他问题的答案。

原件(非常过时)的答案

就是这种情况。 如果你还需要保存密钥,那么适当的function将是uasort

例如:

 usort($array, create_function('$a, $b', 'if ($a["mid"] == $b["mid"]) return 0; return ($a["mid"] < $b["mid"]) ? -1 : 1;')); 

当然,如果你不介意的话,你可以正确地声明比较函数:

 function compareMid($a, $b) { if ($a['mid'] == $b['mid']) { return 0; } return ($a['mid'] < $b['mid']) ? -1 : 1; } 

像这样使用它:

 usort($array, 'compareMid'); 

所有这些都在文档中。