You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP实现3个单词的不同排列方式布局展示

PHP实现多单词全排列展示代码

要实现3个单词的所有排列输出,你可以用递归生成全排列的方案,代码如下:

<?php
// 全排列生成函数
function permute($items, $permutation = []) {
    static $result = [];
    if (empty($items)) {
        $result[] = $permutation;
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
            $newItems = $items;
            $newPermutation = $permutation;
            list($foo) = array_splice($newItems, $i, 1);
            array_unshift($newPermutation, $foo);
            permute($newItems, $newPermutation);
        }
    }
    return $result;
}

// 传入需要排列的3个单词
$words = ['book', 'help', 'air'];
$allPermutations = permute($words);

// 页面布局输出,可自行修改style参数调整样式
echo '<div style="line-height: 2;font-size: 16px;padding: 20px;">';
foreach ($allPermutations as $item) {
    echo implode(' ', $item) . '<br>';
}
echo '</div>';
?>

运行代码后会输出全部6种不重复的排列结果,覆盖所有可能的排序组合:

  • book help air
  • book air help
  • help book air
  • help air book
  • air book help
  • air help book

内容的提问来源于stack exchange,提问作者sa eu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:42:00