我正在尝试创建一个随机播放功能,以便让人们进行礼品交换。我创建了它的基本外壳,我不确定从哪里开始。我正在获取输出以调整数据,但是我想要将array_give
和array_receive
变量结合起来,以便它可以输出以下内容:
array_give
变量不需要改组,只需要array_receive
变量。
还有办法确保结果不会显示如下吗?
保罗&贝基正在给保罗&贝基这是我的代码。任何帮助将不胜感激。
HTML
<button type="button" id="shuffle">Create Exchange</button>
<div id="name-output"></div>
JS
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
$('#name-output').html(data);
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
})
PHP
$array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
$array_receive = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
shuffle($array_receive);
foreach( $array_receive as $receiving) {
echo $receiving . "<br>";
}
答案 0 :(得分:2)
由于数组基本相同,因此只需要一个数组。
然后你可以在每次迭代时弹出/挑选每个元素,这将停止自我赠送,并允许检查某人不会收到礼物,bah欺骗!
<?php
$array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
shuffle($array_give);
$i = 0;
while ($give = array_pop($array_give)) {
echo $give;
if ($i % 2 != 0) {
echo "<br>".PHP_EOL;
} elseif (count($array_give) == 0) {
echo ' is getting zilch! ';
break;
} else {
echo ' are giving to ';
}
$i++;
}
Rob & Savannah are giving to Ashley & Jeric<br>
Dave & Lauren are giving to Keith & Jackie<br>
Paul & Becky is getting zilch!
答案 1 :(得分:1)
组合到数组的函数称为array_combine
。你可以阅读它https://dev.mysql.com/doc/refman/5.7/en/privilege-changes.html,并像这样使用它:
<?php
function checkSame ($a, $b) {
foreach (array_combine($a,$b) as $key => $value)
if ($key===$value) return true;
return false;
}
$array_give = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
$array_receive = array('Paul & Becky', 'Keith & Jackie', 'Dave & Lauren', 'Ashley & Jeric', 'Rob & Savannah');
while (checkSame($array_give, $array_receive)) shuffle($array_receive);
foreach( array_combine($array_give, $array_receive) as $give => $receiving)
{
echo $give. " give to ".$receiving . "<br>";
}
我防止自我礼物的想法是简单地继续洗牌,直到没有人被分配给自己。从理论上讲,这可能会永远存在,但我认为对于大多数实际应用来说,它会很快停止。