我正在尝试开发一种算法来创建symfony模板服务。 我想检查路径子集中是否存在模板,是否已订购。
给出一个像这样的参数数组(已经按照我的意愿排序):
$params = ['O', 'U', 'W', 'P']
如何输出此数组?
$urls = [
'O/U/W/P/template',
'O/U/W/template',
'O/U/P/template',
'O/U/template',
'O/W/P/template',
'O/W/template',
'O/P/template',
'O/template',
'U/W/P/template',
'U/W/template',
'U/P/template',
'U/template',
'W/P/template',
'W/template',
'P/template',
'template'
];
我可以使用如下代码执行一些参数列表(就像每个人都可以这样做):
private function getPaths($template, $params)
{
$urls = [];
$alreadyPerform = [];
$paramsCounter = count($params);
for ($i = 0; $i < $paramsCounter; $i++) {
for ($j = 0; $j < $paramsCounter; $j++) {
if ($i !== $j && !in_array($params[$j], $alreadyPerform, true)) {
$urls[] = sprintf(
'/%s/%s/%s.html.twig', $params[$i], $params[$j], $template
);
}
}
$alreadyPerform[] = $params[$i];
$urls[] = sprintf('/%s/%s.html.twig', $params[$i], $template);
}
$urls[] = sprintf('%s.html.twig', $template);
return $urls;
}
这个功能就像我今天想要的那样工作(最多3个参数),但我想今天添加一个参数,可能更多。
非常感谢你的帮助!
干杯。
答案 0 :(得分:2)
使用递归,您可以执行以下操作:
/**
* @param array $elements
* @param array $extra
*
* @return Generator
*/
function gen(array $elements, array $extra = []): \Generator {
foreach ($elements as $i => $head) {
foreach (gen(array_slice($elements, $i + 1), $extra) as $tail) {
yield array_merge([$head], $tail);
}
}
yield $extra;
}
或者没有递归:
/**
* @param array $elements
*
* @return Generator
*/
function gen2(array $elements): \Generator {
for ($num = count($elements), $i = pow(2, $num) - 1; $i >= 1; $i -= 2) {
$r = [];
for ($j = 0; $j < $num; $j += 1) {
if ($i & (1 << ($num - $j - 1))) {
$r[] = $elements[$j];
}
}
yield $r;
}
}
答案 1 :(得分:1)
考虑使用以下包:
https://github.com/drupol/phpermutations
只是它能做什么的一个非常基本的例子:
$permutations = new \drupol\phpermutations\Generators\Permutations(['A', 'B', 'C'], 2);
foreach ($permutations->generator() as $permutation) {
echo implode('/', $permutation);
echo "\n";
}
A/B
B/A
A/C
C/A
B/C
C/B