How to shuffle an array in PHP while still knowing the original index?

不羁的心 提交于 2019-12-13 07:16:28

问题


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?


回答1:


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;
    }



回答2:


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.



来源:https://stackoverflow.com/questions/34842331/how-to-shuffle-an-array-in-php-while-still-knowing-the-original-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!