如何在仍然知道原始索引的同时在PHP中对数组进行洗牌?

如何在仍然知道原始索引的同时在PHP中对数组进行洗牌?

问题描述:

How do you shuffle a PHP array while still knowing the original index?

I have a simple array in PHP (e.g. ["a", "b", "c", [5, 10]]).

The shuffle() function allows you to shuffle the elements.

However I still wish know what the original index was. How can I do this?

如何在知道原始索引的同时改组PHP数组? p>

我在PHP中有一个简单的数组(例如 [“a”,“b”,“c”,[5,10]] code>)。 p>

shuffle() code>函数允许您随机播放元素。 p>

但是我仍然希望知道原始索引是什么。 我该怎么做? p> div>

See shuffle doc 2nd example:

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }

Do you mean shuffle the elements and keep them with their keys, so if you foreach over them they come out in a shuffled order? That's possible by reshaping the array into a list of [key, value] pairs:

$pairs = array_map(null, array_keys($array), array_values($array));

So ["a", "b", "c", [5, 10]] becomes [[0, "a"], [1, "b"], [2, "c"], [3, [5, 10]].

Then, shuffle the pairs:

shuffle($pairs);

Which might end up something like this (random each time obviously):

[[2, "c"], [1, "b"], [3, [5, 10]], [0, "a"]]

Finally, re-shape it into a normal array again:

$shuffled = array_combine(array_column($pairs, 0), array_column($pairs, 1));

End result looks something like this:

[2 => "c", 1 => "b", 3 => [5, 10], 0 => "a"]

Is that what you want?

This is just one way to do it, though. What Gerard suggested is probably more efficient.