PHP Random Shuffle Array Maintaining Key => Value

后端 未结 10 1211
轮回少年
轮回少年 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 19:51

    I was having a hard time with most of the answers provided - so I created this little snippet that took my arrays and randomized them while maintaining their keys:

    function assoc_array_shuffle($array)
    {
        $orig = array_flip($array);
        shuffle($array);
        foreach($array AS $key=>$n)
        {
            $data[$n] = $orig[$n];
        }
        return array_flip($data);
    }
    

提交回复
热议问题