如何解决PHP模板字符串中关联数组的所有组合?
在这种用例中,我需要将数组的所有组合写入给定的模板字符串中。
即:
// can have as many identifier keys 'A','B','C',etc
$arr = [
'A' => [
// can have as many replacement values
'A1','A2'
],'B' => [
'B1','B2'
]
];
$template = 'A B A';
// returns an array of strings like output below
$genStrings = generateStrings($arr,$template);
// Output
// A1 B1 A1
// A1 B1 A2
// A2 B1 A1
// A2 B1 A2
// A1 B2 A1
// A1 B2 A2
// A2 B2 A1
// A2 B2 A2
外面有灯吗?昨晚一直在努力做到这一点,没有运气。
谢谢!
解决方法
我将使用一个递归函数,将第一项的所有可能值与其余项的所有可能排列组合起来。
注意:PHP 7.4代码,但是可以根据需要轻松地使其与以前的版本兼容。
/**
* @param mixed[] $inputArray
* @param int[]|string[] $template
* @return mixed[][]
*/
function computePermutations(array $inputArray,array $template): array
{
$permutations = [];
$lastPass = count($template) === 1;
foreach ($inputArray[$template[0]] as $firstPermutation) {
if ($lastPass) {
$permutations[] = [$firstPermutation];
}
else {
foreach (computePermutations($inputArray,array_slice($template,1)) as $restPermutation) {
$permutations[] = [$firstPermutation,...$restPermutation];
}
}
}
return $permutations;
}
用法:
$permutations = computePermutations($arr,explode(' ',$template));
$permutationsAsStrings = array_map(fn($permutation) => implode(' ',$permutation),$permutations);
print_r($permutationsAsStrings);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。