【发布时间】:2014-12-10 15:18:04
【问题描述】:
我制作了一套非常简单的纸牌。我正在使用 3 个数组,$deck、$cards 和 $used。 $deck 是游戏中的牌,$cards 是比较数组,$used 是弃牌数组。当从 $deck 中使用卡片时,它们会放在 $used 数组中。我的问题是当它们被放置在 $used 数组中时,它们会按数字顺序排列。我不想要这个。我需要它们的顺序与它们从 $deck 数组中删除的顺序相同。完整代码如下。
<?php
/*
This code creates a deck of cards and deals them
It also creates a discard pile of used cards. It never
deals duplicates and will re-shuffle the deck if it
gets under 7 cards.
*/
dealCards();
/*
This function creates the deck of cards.
It will deal out 5 cards and remove those
5 cards from the deck.
*/
function dealCards() {
// checks to see if a session has been created
if (isset($_SESSION["deck"])) {
$deck = $_SESSION["deck"];
} else {
// if session has not been created it
$deck = range(1, 52);
shuffle($deck);
$_SESSION["deck"] = $deck;
}
// comparison array.
$cards = range(1, 52);
// will use the same deck until it has 7 or less cards
if (count($deck) > 7) {
// deals 5 cards from the array $deck
for ($i = 0; $i < 5; $i++) {
print "<img src="/main/deck/$deck[$i].png" alt="Card: $deck[$i]" />";
// removes dealt cards from the deck
unset($deck[$i]);
// clears empty values from the array
$deck = array_values(array_filter($deck));
// replaces session data with new deck
$_SESSION["deck"] = $deck;
}
} else {
// shuffle the full 52 cards again if the deck is less than 7 cards
$deck = range(1, 52);
shuffle($deck);
$_SESSION["deck"] = $deck;
}
/*
compares $deck to the comparison array $cards
and places the differences in an array
called $used which then can be used as a discard
pile.
*/
$used = array_diff($cards, $deck);
// testing purposes.
print "<pre>";
print_r ($deck);
print "</pre>";
print "<pre>";
print_r ($used);
print "</pre>";
}
?>
【问题讨论】:
-
如果您需要以相同的顺序排列它们,请将数组也存储在会话中。在
unset($deck[$i]);之前的那一刻,做一个$_SESSION['used'][] = $deck[$i];。如果没有地方存储卡片的使用顺序,您永远无法以相同的顺序“重建”那个确切的数组。 -
我尝试了你的建议,他们仍然按数字顺序填充 $used 数组。
-
然后you're doing something wrong,或者您正在使用它做其他事情,导致重新排序。开箱即用,它就像链接代码中所示的那样工作。
-
我让它工作了,但是它只在 $used 数组中保存了 5 张卡片。每次发牌都会用新发的 5 张牌替换之前的 5 张牌。我试图让每张牌都用 $used 直到牌组重新洗牌。
-
你在某处覆盖
$_SESSION['used']。这可能有两个主要原因:(1) 一个逻辑错误,确实在某处重置了$_SESSION['used'](2) 你可能启用了register_globals(从 PHP 5.3.0 起已弃用,从 PHP 5.4 起已删除。 0.) 并且您在某处使用了$used变量。