PHP Random Shuffle Array Maintaining Key => Value

后端 未结 10 1173
轮回少年
轮回少年 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:52

    I tried the most vote solution didn't popular shuffle list. This is the change I made to make it work. I want my array key starting from 1.

     $list = array_combine(range(1,10),range(100,110));
     $shuffle_list =  shuffle_assoc($list);
    
    
    function shuffle_assoc($list)
    {
        if (!is_array($list)) return $list;
    
        $keys = array_keys($list);
        shuffle($list);
        $random = array();
        foreach ($keys as $k => $key) {
            $random[$key] = $list[$k];
        }
        return $random;
    }
    

提交回复
热议问题