我有一個程序,可以從普通卡組中發出10張隨機卡(並且不會將它們放回)。
有時,當我在我收到以下錯誤消息shell中運行該腳本:php - 我收到「未定義的偏移量」錯誤消息,我不知道爲什麼?
PHP Notice: Undefined offset: ..... on line 15
我的代碼如下:
<?php
$deck = array(
array('A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'), //club
array('A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'), //spade
array('A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K'), //heart
array('A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K') //diamond
);
$i = 0;
for ($i = 1; $i <= 10; $i++) {
$a = rand(0, 3); //card's suit
$nr = count($deck[$a]); //how many cards of the suit are available?
$b = rand(0, $nr--); //pick a random number out of the available ones
$card = $deck[$a][$b]; //pick a card [---LINE 15---]
switch ($a) {
case 0:
$c = "club";
break;
case 1:
$c = "spade";
break;
case 2:
$c = "heart";
break;
case 3:
$c = "diamond";
break;
}
echo $c . " " . $card . "\n" . "remaining: " . $nr . "\n";
unset($deck[$a][$b]); //remove the card you drew
array_values($deck[$a]); //rearrange the index of the suit you drew the card from
}
?>
有人能幫助新手嗎?
爲什麼不打印$ a和$ b來檢查它返回的內容?然後嘗試查找該套牌是否具有該索引 – Exprator
因爲你是'unset()'牌。它們不再存在於數組中。你的腳本可能會嘗試給出重複的卡片。 – BlitZ
'$ nr - '只在調用rand函數後遞減,你必須使用' - $ nr'或者'$ nr-1'。 – xander