PHP Random Shuffle Array Maintaining Key => Value

后端 未结 10 1207
轮回少年
轮回少年 2020-11-27 19:21

I\'ve been looking on google for the answer but can\'t seem to find something fool-proof and cant really afford to mess this up (going live into a production site).

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 20:03

    Answer using shuffle always return the same order. Here is one using random_int() where the order is different each time it is used:

    function shuffle_assoc($array)
    {
        while (count($array)) {
            $keys = array_keys($array);
            $index = $keys[random_int(0, count($keys)-1)];
            $array_rand[$index] = $array[$index];
            unset($array[$index]);
        }
    
        return $array_rand;
    }
    

提交回复
热议问题