我有这个数组
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]
排序这个数组
我该怎么做?
目前我在foreach循环中对此进行排序 必须有更好的方法
修改 我希望输出像
这样的东西 [mid] key => array value
由于
答案 0 :(得分:53)
答案 1 :(得分:33)
另一种解决方案是使用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);
?>
答案 2 :(得分:5)
我最近在关于排序多维数组的“权威”主题中以更有能力的方式提出了这个问题answered。下面的答案针对旧版本的PHP(5.2及更早版本);虽然这个概念是合理的,但现在有更好的做事方式。请改为阅读其他问题的答案。
usort
就是出于这种情况。如果您还需要保留密钥,则相应的功能为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');
所有这些都在文档中。