如何创建递归函数来创建最终数组?

时间:2016-02-11 02:28:23

标签: php arrays recursion foreach

这个问题只是打了我的脸,我不是一个伟大的开发人员,就像我以为我是:)我无法弄清楚如何解决它。我假设应该有一个递归函数来执行此操作,但我对任何想法持开放态度。

基本上我有一个从用户输入生成的数组。

$answers = [
  'city' => ["Los Angeles", "San Diego", "Hollywood"],  
  'make' => ["Ferrari", "Bugatti", "Lamborghini"],
];

另一个与" city"相关联的阵列和"制作"答案。

$template = [
    ["Campaign L", "Best [make] in [city]", "Active"],
    ["Campaign O", "Cheap [make] in [city]", "Pause"],
    ["Campaign V", "Top [make] in [city]", "Active"],
    ["Campaign E", "[make] [city]", "Pause"],
    ["Campaign C", "Buy Now [make] in [city]", "Active"],
    ["Campaign A", "Sale [make] [city]", "Active"],
    ["Campaign R", "Fast [make] in [city]", "Active"],
    ["Campaign S", "Red [make] [city]", "Active"],
];

我尝试做的是创建一个最终输出,我替换模板中的每个答案并生成一个主输出。我有一个替换标签的功能,所以我不担心那个部分,但我无法弄清楚如何循环每个组合。

应该有每个城市的组合,所以我的最终输出应该是这样的:

$finalOutput = [
    ["Campaign L", "Best Ferarri in Los Angeles", "Active"],
    ["Campaign O", "Cheap Ferarri in Los Angeles", "Pause"],
    ["Campaign V", "Top Ferarri in Los Angeles", "Active"],
    ["Campaign E", "Ferarri Los Angeles", "Pause"],
    ["Campaign C", "Buy Now Ferarri in Los Angeles", "Active"],
    ["Campaign A", "Sale Ferarri Los Angeles", "Active"],
    ["Campaign R", "Fast Ferarri in Los Angeles", "Active"],
    ["Campaign S", "Red Ferarri Los Angeles", "Active"],
    ["Campaign L", "Best Bugatti in Los Angeles", "Active"],
    ["Campaign O", "Cheap Bugatti in Los Angeles", "Pause"],
    ["Campaign V", "Top Bugatti in Los Angeles", "Active"],
    ["Campaign E", "Bugatti Los Angeles", "Pause"],
    ["Campaign C", "Buy Now Bugatti in Los Angeles", "Active"],
    ["Campaign A", "Sale Bugatti Los Angeles", "Active"],
    ["Campaign R", "Fast Bugatti in Los Angeles", "Active"],
    ["Campaign S", "Red Bugatti Los Angeles", "Active"],
    ...
    ...
    ...
    ...
   and goes on with other combinations...
];

我正在寻找一个解决方案,当答案数组中有三个项目时它也应该有效(例如:[make] [model] [city])。我怎样才能做到这一点?任何想法都赞赏!

由于

1 个答案:

答案 0 :(得分:1)

这是一个更正版本。有点草率,只是寻求最快的解决方案,但它应该给你一个开始的地方。

foreach($template as $fields => $rows) {

    $fields = explode(' ', $fields);

    foreach($fields as $i => $field) {
        $replacements[$i] = $answers[$field];
    }

    $first_answers = array_shift($replacements);
    $first_field   = array_shift($fields);

    for($i = 0; $i < count($first_answers); $i++) {
        foreach($replacements as $j => $values) {
            foreach($values as $replacement) {
                foreach($rows as $row) {
                    $new_row = [];
                    foreach($row as $col => $text) {
                        $text = str_replace('['.$first_field.']', $first_answers[$i], $text);
                        $text = str_replace('['.$fields[$j].']', $replacement, $text);
                        $new_row[] = $text;
                    }
                    $finalOutput[] = $new_row;
                }
            }
        }
    }
}