从关联数组中随机选取

时间:2015-02-07 15:43:12

标签: php arrays

我正在用PHP制作二十一点游戏。所以我制作了一个具有所有卡名和值的关联数组。看起来像这样:

$cards = array("Schoppen 2"=>"2", "Schoppen 3"=>"3", "Schoppen 4"=>"4", "Schoppen 5"=>"5", "Schoppen 6"=>"6", "Schoppen 7"=>"7", "Schoppen 8"=>"8", "Schoppen 9"=>"9", "Schoppen 10"=>"10"
            , "Schoppen boer"=>"10", "Schoppen vrouw"=>"10", "Schoppen heer"=>"10", "Schoppen aas"=>"11", "Harten 2"=>"2", "Harten 3"=>"3", "Harten 4"=>"4", "Harten 5"=>"5", "Harten 6"=>"6", "Harten 7"=>"7", "Harten 8"=>"8", "Harten 9"=>"9", "Harten 10"=>"10"
            , "Harten boer"=>"10", "Harten vrouw"=>"10", "Harten heer"=>"10", "Harten aas"=>"11", "Klaveren 2"=>"2", "Klaveren 3"=>"3", "Klaveren 4"=>"4", "Klaveren 5"=>"5", "Klaveren 6"=>"6", "Klaveren 7"=>"7", "Klaveren 8"=>"8", "Klaveren 9"=>"9", "Klaveren 10"=>"10"
            , "Klaveren boer"=>"10", "Klaveren vrouw"=>"10", "Klaveren heer"=>"10", "Klaveren aas"=>"11", "Ruiten 2"=>"2", "Ruiten 3"=>"3", "Ruiten 4"=>"4", "Ruiten 5"=>"5", "Ruiten 6"=>"6", "Ruiten 7"=>"7", "Ruiten 8"=>"8", "Ruiten 9"=>"9", "Ruiten 10"=>"10"
            , "Ruiten boer"=>"10", "Ruiten vrouw"=>"10", "Ruiten heer"=>"10", "Ruiten aas"=>"11");

现在我想为玩家挑选2张牌,为经销商挑选2张牌,所以即时使用:

$playercards = array_rand($cards, 2);
$dealercards = array_rand($cards, 2);

但现在如果我回复$playercards它是空的。有人看到了这个问题吗?因为我以前没用过array_rand。

卡也可能不一样。所以一旦一个人被选中,他就不能再被array_rand选中了,是否还有机会解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:2)

既然你正在打牌,为什么不使用shuffle功能?

shuffle( $cards );
$card_player_1 = array_shift( $cards );
$card_player_2 = array_shift( $cards );
$card_dealer_1 = array_shift( $cards );
$card_dealer_2 = array_shift( $cards );

由于array_shift

,这些卡片将不在数组中

<强>更新

如果你想保留密钥,文档中有一篇文章解释了如何实现它:

  

在保留键的同时随机关联和非关联数组,   价值对。还返回洗牌数组而不是洗牌   到位。

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; 
}

然后你的代码:

$cards_shuffled = shuffle_assoc( $cards );
$card_player_1 = array_shift( $cards_shuffled);
$card_player_2 = array_shift( $cards_shuffled );
$card_dealer_1 = array_shift( $cards_shuffled );
$card_dealer_2 = array_shift( $cards_shuffled );

如果要将键和值存储在不同的变量中,可以使用以下方法:

$cards_shuffled = shuffle_assoc($cards);
list($card_player_1_key, $card_player_1_value) = each($cards_shuffled);
array_shift($cards_shuffled);
list($card_player_2_key, $card_player_2_value) = each($cards_shuffled);
array_shift($cards_shuffled);
list($card_dealer_1_key, $card_dealer_1_value) = each($cards_shuffled);
array_shift($cards_shuffled);
list($card_dealer_2_key, $card_dealer_2_value) = each($cards_shuffled);
array_shift($cards_shuffled);

echo $card_player_1_key;// Print key of player 1 card.
echo $card_player_1_value;// Print value of player 1 card.
echo $card_dealer_2_key;// Print key of dealer second card.