PHP Random Shuffle Array Maintaining Key => Value

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

    The first user post under the shuffle documentation:

    Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

    function shuffle_assoc($list) { 
      if (!is_array($list)) return $list; 
    
      $keys = array_keys($list); 
      shuffle($keys); 
      $random = array(); 
      foreach ($keys as $key) { 
        $random[$key] = $list[$key]; 
      }
      return $random; 
    } 
    

    Test case:

    $arr = array();
    $arr[] = array('id' => 5, 'foo' => 'hello');
    $arr[] = array('id' => 7, 'foo' => 'byebye');
    $arr[] = array('id' => 9, 'foo' => 'foo');
    print_r(shuffle_assoc($arr));
    print_r(shuffle_assoc($arr));
    print_r(shuffle_assoc($arr));
    

提交回复
热议问题