如何使用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
相关产品推荐
相关产品推荐

