高效的方式来自字符串的特定组合

时间:2016-06-23 17:21:32

标签: php combinations

所以我有一个这样的短语:

one_two_three_four

..为了清楚起见,它也可能是这样的:

one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve

..但为了简洁起见,我将以此为例:

one_two_three_four

从字符串中,我想创建以下关键字

one
one_two
one_two_three
two
two_three
two_three_four
three
three_four
four

我正在寻找最有效的方法(在PHP中)来解析这样的字符串(有些会更大)。

我可以做到这一点:

$keyword = explode('_', $string);

所以现在我有一个像这样的数组:

one
two
three
four

我被困在如何从原始字符串到变体。

1 个答案:

答案 0 :(得分:3)

首先需要按_

分解字符串
$str = 'one_two_three_four_five_six';
$array = explode('_', $str);

添加一个空数组以存储结果

$result = [];

定义一个递归函数,它接受一个数组,内爆数组值,删除最后一个元素并调用相同的数组直到长度为0

function visitArray($array, &$result) {
    if(count($array) == 0) //Check if length is 0 (Stop executing)
        return;
    $result[] = implode('_', $array); //Implode array values
    return visitArray(array_slice($array, 0, count($array) -  1), $result); //Remove last element and call again the same function
}

因此,如果您将[1, 2, 3]传递给 visitArray ,您将拥有 结果数组中的1_2_31_21

现在您需要辅助功能来调用visitArray新职位

这意味着,如果我们有这个数组[1, 2, 3]

我们需要致电 visitArray [1,2,3][2,3][3]

因此我们定义一个带有简单for循环的函数来迭代数组值,每次调用 visitArray()时我们都会使用带有position变量的array_slice忽略调用一次。

function callVisit($array, &$result, $position = 0) {
    for($i = 0; $i < count($array); $i++)
        visitArray(array_slice($array, $position++, count($array) - 1), $result);
}

<强>更新 如果你需要删除位置参数,你可以用下面的列表替换forloop:

function callVisit($array, &$result) {
    while (list(,$v) = each($array)) 
    { 
        visitArray($array, $result);
        array_shift($array); //Remove first element
    } 
}

所以你需要通过传递两个参数来调用callVisit(),数组,结果数组(应该存储结果)

callVisit($array, $result);

完整代码:

<?php

$str = 'one_two_three_four_five_six';

$array = explode('_', $str);

$result = [];


function callVisit($array, &$result, $position = 0) {
    for($i = 0; $i < count($array); $i++) 
        visitArray(array_slice($array, $position++, count($array) - 1), $result);
}

function visitArray($array, &$result) {
    if(count($array) == 0)
        return;
    $result[] = implode('_', $array);
    return visitArray(array_slice($array, 0, count($array) -  1), $result);
}


callVisit($array, $result);

echo "<pre>", json_encode($result, JSON_PRETTY_PRINT), "</pre>";