0

文字列インデックス付き連想配列からランダム配列を取得しようとしています。コードは次のとおりで、エラーが発生し続けます。

$suite['heart']=1;
$suite['heart']=2;
$suite['heart']=3;
$suite['heart']=4;
$suite['heart']=5;

$rand = array_rand($suite);
$card1 = $suite[$rand];

print $card1;

私の結果は静的で、連続して 5 を表示していました。任意の乱数を表示したいと考えています。

前もって感謝します!

4

1 に答える 1

1

That is because all that $suite['heart'] contains is 5.

You are declaring $suite['heart'] = 1; then redeclaring $suite['heart'] = 2; etc.

I think what you are looking for in your array is something more like

$suite['heart'] = array(1, 2, 3, 4, 5);

Also note that $rand = array_rand($suite); will only ever retrieve a direct child of $suite (always $suite['heart'] if you don't have any others defined) - you will also have to pick a random value from the sub-array to get a random suit and number.

The following should work:

$suite['heart'] = array(1, 2, 3, 4, 5);
$suite['spade'] = array(1, 2, 3, 4, 5);

$suit = array_rand($suite);
$card = array_rand($suite[$suit]);
$card1 = $suite[$suit][$card];

print $card1;
于 2013-09-18T02:18:06.623 に答える