1 回答
TA贡献2080条经验 获得超4个赞
该算法非常简单。在移动第一个元素后,您可以简单地使用 while 语句循环剩余的条目,然后使用 2 个其他循环按顺序附加剩余的名称:
$names = ["Jim", "Jane", "Bob", "Susan", "Ralph"];
$result = [];
while (count($names) > 2) {
$currentName = array_shift($names);
for ($i = 0; $i < count($names) - 1; $i++) {
for ($j = $i + 1; $j < count($names); $j++) {
$result[] = implode(', ', [$currentName, $names[$i], $names[$j]]);
}
}
}
var_dump($result);
结果将是:
array(10) {
[0]=>
string(14) "Jim, Jane, Bob"
[1]=>
string(16) "Jim, Jane, Susan"
[2]=>
string(16) "Jim, Jane, Ralph"
[3]=>
string(15) "Jim, Bob, Susan"
[4]=>
string(15) "Jim, Bob, Ralph"
[5]=>
string(17) "Jim, Susan, Ralph"
[6]=>
string(16) "Jane, Bob, Susan"
[7]=>
string(16) "Jane, Bob, Ralph"
[8]=>
string(18) "Jane, Susan, Ralph"
[9]=>
string(17) "Bob, Susan, Ralph"
}
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报