我有一个如下所示的PHP数组:http://pastie.org/1346063(有关数组示例,请参阅pastie)
我想要做的是将该数组重新排序为另一个数组,该数组按每个数组的[votes] [POINTS]子数组按数字递减排序。具有最高[votes] [POINTS]值的数组将是主数组中列出的第一个数组。
答案 0 :(得分:3)
使用usort()
函数,我们可以创建自己的比较函数:
function cmp($a, $b) {
if($a['votes']['POINTS'] == $b['votes']['POINTS']) {
return 0;
}
return ($a['votes']['POINTS'] < $b['votes']['POINTS']) ? 1 : -1;
}
usort($array, 'cmp');
<强>结果:强>
使用与您的结构类似的测试数据:
Array
(
[0] => Array
(
[votes] => Array
(
[UP] => 1
[DOWN] => 0
[POINTS] => 5
)
)
[1] => Array
(
[votes] => Array
(
[UP] => 1
[DOWN] => 0
[POINTS] => 4
)
)
[2] => Array
(
[votes] => Array
(
[UP] => 1
[DOWN] => 0
[POINTS] => 2
)
)
[3] => Array
(
[votes] => Array
(
[UP] => 1
[DOWN] => 0
[POINTS] => 1
)
)
)
答案 1 :(得分:0)
<强>解决方案强>: -
假设您的数组存储在名为 $ data
的变量中您只需使用array_multisort
对多维数组进行排序即可foreach ($data as $key => $row) {
$points[$key] = $row['votes']['points'];
}
// Sort the data with points descending
array_multisort($points, SORT_DESC, $data);
希望这有帮助。