我希望创建一个小的脚本来生成一对用户。
用户位于一个数组中,因此我使用shuffle将它们随机配对。
我的问题是我想在最终结果中避免/排除一些用户对。
所以我有第一部分来洗牌用户:
<?php
$user[] = "Miaa";
$user[] = "Xavier";
$user[] = "Antoine";
$user[] = "Marie-Ange";
$user[] = "Claire";
$user[] = "Orlando";
$user[] = "Camille";
$user[] = "Chloé";
$user[] = "Audrey";
$user[] = "*";
$users = count($user);
// Shuffle user
shuffle($user);// You get a shuffled array
// Pair the adjacent user
for ( $index = 0; $index < $users; $index +=2) {
// Pair $user[$index ] with $user[$index +1]
echo $user[$index ] . " <=> " . $user[$index+1] . "\n";
}
?>
这是我的代码到沙箱的链接=> http://sandbox.onlinephpfunctions.com/code/6ef04e99946849606544493e64e317206209c10c
我试图添加一个if语句,但没有成功
$user[$index[0]] == "Miaa" && $user[$index[1]] == "Xavier"
答案 0 :(得分:0)
u可以获取所有组合,然后通过随机键获取它:)
<?php
$user[] = "Miaa";
$user[] = "Xavier";
$user[] = "Antoine";
$user[] = "Marie-Ange";
$user[] = "Claire";
$user[] = "Orlando";
$user[] = "Camille";
$user[] = "Chloé";
$user[] = "Audrey";
$user[] = "*";
$shufla = [];
foreach ($user as $us1) {
foreach ($user as $us2) {
if (
("Miaa" === $us1 and "Xavier" === $us2) ||
("Miaa" === $us2 and "Xavier" === $us1) ||
($us1 === $us2)
) continue;
$shufla[] = $us1 . " <=> ". $us2;
}
}
var_dump($shufla[mt_rand(0, count($shufla) - 1)]);
答案 1 :(得分:0)
$firstGroup = [
"Miaa",
"Xavier"
];
$secondGroup = [
"Antoine",
"Marie-Ang",
"Claire",
"Orlando",
"Camille",
"Chloé",
"Audrey",
"*",
];
shuffle($secondGroup);
// calculate how many users should be moved to first group
$usersToMove = (count($secondGroup) + 2) / 2 - 2;
//move random users to first group
for ($i = 0; $i < $usersToMove; $i++) {
$firstGroup[] = array_shift($secondGroup);
}
for ($i = 0; $i < count($firstGroup); $i++) {
echo $firstGroup[$i] . ' <=> ' . $secondGroup[$i];
}
答案 2 :(得分:0)
首先,我创建了变量$err
,以检测是否找到了该对,然后重新开始循环。重新启动循环时,数组$res
的结果为空。我最终解析了数组的结果。
<?php
$user[] = "Miaa";
$user[] = "Xavier";
$user[] = "Antoine";
$user[] = "Marie-Ange";
$user[] = "Claire";
$user[] = "Orlando";
$user[] = "Camille";
$user[] = "Chloé";
$user[] = "Audrey";
$user[] = "*";
$users = count($user);
// Shuffle user
shuffle($user);// You get a shuffled array
// Pair the adjacent user
$err = 1;
$res = array();
while($err > 0){
$err--;
for ( $index = 0; $index < $users; $index +=2) {
if(($user[$index ] == "Miaa" && $user[$index+1] == "Xavier") || ($user[$index ] == "Xavier" && $user[$index+1] == "Miaa")){
$err = 1;
$users = count($user);
shuffle($user);
unset($res);
$res = array();
}else{
//echo $user[$index ] . " <=> " . $user[$index+1] . "\n";
$res[] = [$user[$index ], $user[$index+1]];
}
// Pair $user[$index ] with $user[$index +1]
}
}
$nb_res = count($res);
while($nb_res > 0){
$nb_res--;
$user1 = $res[$nb_res][0];
$user2 = $res[$nb_res][1];
echo $user1 . " <=> " . $user2 . "\n";
}
?>