【问题标题】:All combinations of an associative array in a template string in PHP?PHP中模板字符串中关联数组的所有组合?
【发布时间】:2020-08-15 15:52:01
【问题描述】:

我有一个用例,我需要将数组的所有组合写入给定的模板字符串。

即:

// 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

那里有灯吗?昨晚一直在努力完成这个,没有运气。

谢谢!

【问题讨论】:

  • 您应该扩展模板,然后循环...请发布您的尝试...
  • 我已准备好为您提供可能的解决方案,但事实上,请先分享您的尝试。也许你离你不远,有一种方法可以引导你完成。
  • 用例比仅仅分解模板要复杂得多,我试图混淆 css 选择器,因为选择器中的每个元素都有替换(这个元素是 $arr 和替换的关键是值),那么解决方案将需要模式替换,尽管我已经在这里取得了一些进展。我在这里问这个的原因是为了找出生成字符串所需的最小逻辑。我已经读过一些关于电源装置的东西,这看起来像是一条路。

标签: php arrays string replace


【解决方案1】:

我会使用递归函数,它将第一项的所有可能值与其余项的所有可能排列组合起来。

注意: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);

Demo

【讨论】:

  • 这对我来说是一个很好的起点,我会尝试将此解决方案扩展到模板类似于“A.abc B#io A#123”的情况。我实际上会喜欢这样的东西: $permutations = computePermutations($arr, "A.abc B#io A#123") 这将返回所有输出的字符串 []。不过,我会将您标记为已接受并为此努力:) 谢谢! :)
  • 我可以帮你解决这个问题,但不确定你是否会遵循:.abc#io 这些东西代表什么?你必须举出例子。您也可以将此作为新问题发布(并在此处链接)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多