2014-03-03 104 views
0

我想按值对一个关联数组分组,并随机化每个组的项目。PHP按值分组并随机排序

我有以下的数组$结果

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)中的对象应该是在上面。但建筑应该是每组随机所以第一个ID 之上则ID在上面 ...所以我想随机

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"); 

但是,这并不能保持我的数组按公式分组。

回答

1

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; 
}); 

而且人们面前说我的洗牌“不是真正的随机”,我说:“这是这个应用足够的随机”。

+0

这不起作用,返回的数组仍然有顶部具有公式1的对象。 –