PHP Random Shuffle Array Maintaining Key => Value

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

      $testArray = array('a' => 'apple', 'b' => 'ball', 'c' => 'cat', 'd' => 'dog');
      $keys = array_keys($testArray); //Get the Keys of the array -> a, b, c, d
      shuffle($keys); //Shuffle The keys array -> d, a, c, b
      $shuffledArray = array();
      foreach($keys as $key) {
        $shuffledArray[$key] = $testArray[$key]; //Get the original array using keys from shuffled array
      }
      print_r($shuffledArray);
      /*
      Array
      (
          [d] => dog
          [a] => apple
          [c] => cat
          [b] => ball
      )
      */
    

提交回复
热议问题