设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 204|回复: 0

PHP: Sorting arrays randomly

[复制链接]
发表于 2013-11-5 11:17:55 | 显示全部楼层 |阅读模式
A custom PHP function. This function will return an array that’s been resorted in a random order. Supports both numerically-indexed and associative arrays. Uses PHP’s native array_rand() function.
  1. function array_randsort($array,$preserve_keys=false){
  2.         /*-------------------------------------/
  3.         Preserving the keys works best with associative arrays.
  4.         If you choose to preserve keys on a numerically-indexed or
  5.     mixed-indexed array, use a foreach loop rather than a for loop
  6.     to preserve the sorted order.
  7.         /-------------------------------------*/
  8.        
  9.         if(!is_array($array)):
  10.                 exit('Supplied argument is not a valid array.');
  11.         else:
  12.                 $i = NULL;
  13.        
  14.                 // how long is the array?
  15.                 $array_length = count($array);
  16.        
  17.                 // Sorts the array keys in a random order.
  18.                 $randomize_array_keys = array_rand($array,$array_length);
  19.                
  20.                 // if we are preserving the keys ...
  21.                 if($preserve_keys===true) {               
  22.                         // reorganize the original array in a new array
  23.                         foreach($randomize_array_keys as $k=>$v){
  24.                                 $randsort[$randomize_array_keys[$k]] = $array[$randomize_array_keys[$k]];
  25.                         }
  26.                 } else {
  27.                         // reorganize the original array in a new array
  28.                         for($i=0; $i < $array_length; $i++){
  29.                                 $randsort[$i] = $array[$randomize_array_keys[$i]];
  30.                         }
  31.                 }
  32.                 return $randsort;
  33.         endif;
  34. }
复制代码

There is also a shuffle() function in PHP.  It randomizes arrays also, but destroys the keys in associative arrays .  The other drawback of shuffle() is that it performs its tasks on the actual reference array parameter. So for data integrity a solution like this is probably better.

Copy and paste this script and refresh the page to see the shuffling effect.
  1. <?php
  2.     /**
  3.     * Shuffles and displays cards in a deck
  4.     * @author:     Eric Anderson
  5.     * @filename:   deckofcards.php
  6.     */
  7.    
  8.     // Create an array of face values
  9.     // and an array of card values
  10.     // then merge them together
  11.     $cards = array_merge(array("J", "Q", "K", "A"), range(2,10)); // 13 cards
  12.    
  13.     // Shuffle the cards
  14.     shuffle($cards);
  15.    
  16.     // Create an multidimentional array to hold the 4 suits
  17.     $suits = array(
  18.         'Heart' => array(),
  19.         'Spade' => array(),
  20.         'Diamond' => array(),
  21.         'Club' => array()
  22.         );
  23.       
  24.     // Add cards to their respective suits
  25.     for($i = 0; $i < count($suits); $i++)
  26.     {
  27.         for($j = 0; $j < count($cards); $j++)
  28.         {
  29.             $suits['Heart'][$j] = $cards[$j]."<span style=color:#FF0000;>♥</span>";
  30.             $suits['Spade'][$j] = $cards[$j]."♠";
  31.             $suits['Diamond'][$j] = $cards[$j]."<span style=color:#FF0000;>♦</span>";
  32.             $suits['Club'][$j] = $cards[$j]."♣";
  33.         }
  34.     }
  35.    
  36.     // Create a deck
  37.     $deck = array();
  38.    
  39.     // Merge the suits into the empty deck array
  40.     $deck = array_merge($deck, $suits);
  41.                
  42.     // Display the deck to the screen
  43.     echo "<p><b>Deck of cards:</b></p>";
  44.     foreach($deck as $k1 => $v1)
  45.     {
  46.         // Display suit name
  47.         echo "<p> $k1's<br /> {<br />  ";
  48.         $acc = 0;
  49.       
  50.         // Display card value
  51.         foreach($v1 as $k2 => $v2)
  52.         {
  53.             echo "$v2 ";
  54.             $acc++;
  55.            
  56.             if ($acc == 4)
  57.             {
  58.                 echo "<br />  ";
  59.                 $acc = 0;
  60.             }
  61.         }
  62.         echo "<br /> }</p>";
  63.     }
  64. ?>
复制代码

Tiffany B. Brown

您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-12-12 22:31 , Processed in 0.012321 second(s), 16 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表