Algorithmic issues with php array splitting
習慣沉默
習慣沉默 2017-05-16 13:08:40
0
2
871

Split the string $str = '12,34,5';
Split it into an array $arr = [[1,3,5],[1,4,5],[2,3,5 ],[2,4,5]];
Looking for a PHP logical algorithm to convert $str to $arr;

習慣沉默
習慣沉默

reply all(2)
世界只因有你

Explain that using global may not look that elegant, but here I am just writing an example method. If it is not too confusing, you can optimize it by yourself

$str = '12,34,5';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);


$str = '12,34';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);

$str = '12,34,5,67';
$arr = explode(',', $str);
$step = $book = $result = [];
dfs(0);
print_r($result);
function dfs($s)
{
    global $arr, $step, $result, $book;
    if (!isset($arr[$s])) {
        $result[] = array_values($step);
        return;
    }

    for ($i = 0; $i < strlen($arr[$s]); $i++) {
        if (!isset($book[$s][$i]) || $book[$s][$i] == 0) {
            $book[$s][$i] = 1;
            $step[$s] = $arr[$s][$i];
            dfs($s + 1);
            $book[$s][$i] = 0;
        }
    }
    return;
}
洪涛

Two arrays are easy to combine. Two nested for loops are enough. A multiarray with an uncertain number cannot be processed in this way. You can refer to some sorting algorithm ideas. The multiarray is converted into two through recursion. Array, such as: [[1,2],[3,4],[5]], convert it to [[13,14,23,24],[5]], the last two nested for loops Solution, reference code:


$str = '12,34,5';
$arr = [];
foreach (explode(',', $str) as $v) {
    $arr[] = str_split($v);
}

print_r(fun($arr));

function fun($arr)
{
    if (count($arr) >= 2) {
        $tmparr = [];
        $arr1 = array_shift($arr);
        $arr2 = array_shift($arr);
        foreach ($arr1 as $v1) {
            foreach ($arr2 as $v2) {
                $tmparr[] = $v1 . $v2;
            }
        }
        array_unshift($arr, $tmparr);
        $arr = fun($arr);
    }
    return $arr;
}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template