PHP按值分组并随机排序

时间:2014-03-03 09:23:19

标签: php arrays shuffle usort

我想按值对关联数组进行分组,并将每个项的项目随机化。

我有以下数组$ result

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的对象应该在顶部。但建筑物应该是每组随机的,所以首先在顶部 285 然后在顶部id 120 ...所以我想要随机

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 个答案:

答案 0 :(得分: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;
});

在人们说我的洗牌“不是真的随机”之前,我说“这个应用程序足够随机”。