使用in_array / php卡经销商计划

时间:2013-10-05 20:16:02

标签: php

这让我很难过。基本上我正在尝试交易卡。我得到了正确数量的卡,但它复制了随机生成的卡。相反,如果用户输入52,我需要有52张不同的卡片。

我一直在努力做到这一点,但无法弄明白。我尝试使用in_array函数,但无济于事

有人可以帮忙吗

<?php
$input = $_POST["txtNumberOfCards"];

$suit = array("Hearts", "Diamonds", "Clubs", "Spades");
$card = array("Ace","2", "3","4","5","6","7","8","9","10","Jack","Queen","King");

$randsuit = rand(0,3);
$randcard = rand(0,12);

for($x = 0; $x < $input; $x++){
echo ('<img src="Images/'.$card[$randcard].'of'.$suit[$randsuit].'.gif">');
}

?>

3 个答案:

答案 0 :(得分:1)

使用数组来跟踪已使用的卡片并采取相应措施。同样在你的代码中你有for循环之外的rand函数,这意味着它只会产生一次随机数

$input = $_POST["txtNumberOfCards"];;

$suit = array("Hearts", "Diamonds", "Clubs", "Spades");
$card = array("Ace","2", "3","4","5","6","7","8","9","10","Jack","Queen","King");

$setCards = array();
for($x = 0; $x < $input; $x++){
    $randsuit = rand(0,3);
    $randcard = rand(0,12); 
    if( isset($setCards[$suit[$randsuit].$card[$randcard]]) ) {
        $x--;
        continue;
    }
    echo ('<img src="Images/'.$card[$randcard].'of'.$suit[$randsuit].'.gif">');
    $setCards[$suit[$randsuit].$card[$randcard]] = true;
}

phpFiddle :请注意小提琴回复html,以便可以查看而不是呈现。

答案 1 :(得分:0)

您需要使用函数$input

intval()转换为int变量

此外,每次循环时随机分配varilabel以生成不同的卡片:

<?php
$input = intval($_POST["txtNumberOfCards"]);

$suit = array("Hearts", "Diamonds", "Clubs", "Spades");
$card = array("Ace","2", "3","4","5","6","7","8","9","10","Jack","Queen","King");


for($x = 0; $x < $input; $x++){
$randsuit = rand(0,3);
$randcard = rand(0,12);
echo ('<img src="Images/'.$card[$randcard].'of'.$suit[$randsuit].'.gif">');
}

?>

答案 2 :(得分:0)

您获得重复卡片的原因是因为您没有检查卡片组合是否已经处理过。

最佳解决方案是建立一系列卡片,并用它来检查是否已创建卡片组合。然后回显构建的数组。

<?php
//The user input
$input = $_POST["txtNumberOfCards"];

$suit = array( "Hearts" , "Diamonds" , "Clubs" , "Spades" );
$card = array( "Ace" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" , "Jack" , "Queen" , "King");
//$dealArray holds the cards as they are dealt and used to compare what cards have all ready been dealt
$dealArray= array( );
//$count the while loop counter variable
$count = 0;
//while the $count variable is less then the $input
while( $count < $input )
{
  //generate a card combination array
  $cardCombo = array( 'suit' => $suit[ rand( 0 , 3 ) ],//Generate Random suit
                      'card' => $card[ rand( 0 , 12 ) ] );//Generate Random card

  //if the $cardCombo array that was generated is not in the $dealArray
  if ( !in_array( $cardCombo , $dealArray ) )
  {
    //Add the $cardCombo array to the end of the $dealArray
    array_push( $dealArray , $cardCombo );
    //Output an HTML image for the $cardCombo array
    echo ( '<img src="Images/' . $cardCombo['card'] . 'of' . $cardCombo['suit'] . '.gif">' );
    $count++;//Add 1 to the counter
  }
}
?>