简体   繁体   English

PHP按值分组并随机排序

[英]PHP Group by value and sort randomly

I want to group an associative array by value and randomize the items per group. 我想按值对关联数组进行分组,并按组将项目随机化。

I have the following array $result 我有以下数组$ 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
    )
)

So I want to group the array by its formula so the objects with formula 4 should be on top. 因此,我想按数组的公式对数组进行分组,这样公式4的对象应位于顶部。 But the buildings should be per group random so first id 285 on top then id 120 on top... So I want randomly 但是建筑物应该是每组随机的,所以首先是ID 285在顶部,然后ID 120在顶部...所以我想随机

Aray(
      [0] => Building Object
      (
          [id] => 285
          [formula] => 4
          [title] => test 1
      )

      [1] => Building Object
      (
          [id] => 120
          [formula] => 4
          [title] => test 2
      ) ..

How can I do this I tried: 我该如何尝试:

shulffle($result);
usort($result, "cmp");

But that doesn't keep my array grouped by the formula. 但这并不能使我的数组按公式分组。

usort is the right function, but you need to be more specific: 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;
});

And before people say my shuffling "isn't really random", I say "it's random enough for this application". 在人们说我的改组“不是真的随机”之前,我说“对于这个应用程序来说足够随机”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM