洗牌在PHP中数组的第一个层次 [英] Shuffling the first level of the array in PHP

查看:110
本文介绍了洗牌在PHP中数组的第一个层次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP的洗牌()不是随机的数组,我需要它的方式。我有一个二维数组,当我使用洗牌()上只随机化数组的第二维,但我需要相反的。

PHP's shuffle() is not randomizing an array the way I need it. I have a two dimensional array and when I use shuffle() on it it only randomizes the 2nd dimension of the array, but I need the opposite.

让我们假设这是我需要洗牌数组:

Lets assume this is the array I need to shuffle:

Array
(
    [0] => Array
        (
            [key1] => 199
            [key2] => 6
        )

    [1] => Array
        (
            [key1] => 195
            [key2] => 3
        )

)

洗牌()打乱它的方式是这样的:

The way the shuffle() shuffles it is like this:

Array
(
    [0] => Array
        (
            [key1] => 195
            [key2] => 3
        )

    [1] => Array
        (
            [key1] => 199
            [key2] => 6
        )

)

但是这不是我后。我需要的是一个最终的结果是这样的:

But this is not what I'm after. What I need as an end result is this:

Array
(
    [1] => Array
        (
            [key1] => 195
            [key2] => 6
        )

    [0] => Array
        (
            [key1] => 199
            [key2] => 6
        )

)

我知道,这可以通过使用 mt_rand()随机密钥兰特(可以实现这一点,但它也可能是可能的钥匙少量的,我们可以收到同样的兰特()键两次,导致没有一个很好的洗牌数组。

I know that this can be achieved this using a random key with rand() or mt_rand(), but it also could be possible that for a small amount of keys, we could receive the same rand() key twice, leading to NOT have a nicely shuffled array.

我也知道,增加更多的如果别人逻辑将是一种可能性,但我正在寻找与已经实施的东西,要做到这一点 - 我不想重新发明轮。

I also know that adding more if else logic would be a possibility, but I'm looking to do this with already implemented stuff - I don't wanna reinvent the wheel.

如何才能实现我想要的洗牌?

How can I achieve my desired shuffle?

推荐答案

洗牌()正在按预期。这不是随机第二维,它不是递归的。

shuffle() is working as intended. It is not "randomizing the 2nd dimension", it is not recursive.

据重新排序阵列(其恰好是阵列)的元素。您所看到的问题是,因为洗牌()重置数组的键。

It is reordering the elements of the array (which just happen to be arrays). The issue you are seeing is because shuffle() resets the array's keys.

从文档( http://php.net/shuffle ):

注意:此功能分配新的键在数组中的元素。它会删除可能已分配任何现有的密钥,而不是
  刚刚重新排列的按键。

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

要得到你想要的,你需要使用 array_rand()来随机密钥,然后重新排序的基础上,该数组中的元素。

To get what you want, you need to use array_rand() to randomize the keys, then reorder the elements in the array based on that.

$randKeys = array_rand($array, count($array));
// This is needed because array_rand was changed
// and now returns the keys in order
shuffle($randKeys);

uksort($array, function($a, $b) use($randKeys){
    return array_search($a, $randKeys) - array_search($b, $randKeys);
});

DEMO: https://eval.in/101265

这篇关于洗牌在PHP中数组的第一个层次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆