Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP按值分组并随机排序_Php_Arrays_Shuffle_Usort - Fatal编程技术网

PHP按值分组并随机排序

PHP按值分组并随机排序,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

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

我有以下数组$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的对象应该在上面。但是建筑应该是每组随机的,所以首先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的对象。。