PHP按值分组并随机排序
我想按值对关联数组进行分组,并随机化每组的项 我有以下数组$resultPHP按值分组并随机排序,php,arrays,shuffle,usort,Php,Arrays,Shuffle,Usort,我想按值对关联数组进行分组,并随机化每组的项 我有以下数组$result Aray( [0] => Building Object ( [id] => 285 [formula] => 4 [title] => test 1 ) [1] => Building Object ( [id] => 120 [formula] => 4
Aray(
[0] => Building Object
(
[id] => 285
[formula] => 4
[title] => test 1
)
[1] => Building Object
(
[id] => 120
[formula] => 4
[title] => test 2
)
[2] => Building Object
(
[id] => 199
[formula] => 2
[title] => test 3
)
[3] => Building Object
(
[id] => 231
[formula] => 1
[title] => test 4
)
[3] => Building Object
(
[id] => 230
[formula] => 1
[title] => test 5
)
)
所以我想按公式对数组进行分组,这样公式为4的对象应该在上面。但是建筑应该是每组随机的,所以首先id285在顶部,然后id120在顶部。。。所以我想要随机的
Aray(
[0] => Building Object
(
[id] => 285
[formula] => 4
[title] => test 1
)
[1] => Building Object
(
[id] => 120
[formula] => 4
[title] => test 2
) ..
我怎样才能做到这一点我试过:
shulffle($result);
usort($result, "cmp");
但这并不能使我的数组按公式分组。
usort
是正确的函数,但您需要更具体一些:
// drop the `shuffle`, we'll be shuffling in the sort
usort($result,function($a,$b) {
// PHP 5.4 or newer:
return ($a->formula - $b->formula) ?: rand(-1,1);
// older PHP:
if( $a->formula == $b->formula) return rand(-1,1);
return $a->formula - $b->formula;
});
在人们说我的洗牌“不是真正随机的”之前,我会说“它对于这个应用程序来说已经足够随机了”。这不起作用,返回的数组仍然有上面有公式1的对象。。