search

Home  >  Q&A  >  body text

Algorithmic issues with php array splitting

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;

習慣沉默習慣沉默2753 days ago839

reply all(2)I'll reply

  • 世界只因有你

    世界只因有你2017-05-16 13:10:40

    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;
    }

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:10:40

    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;
    }
    
    

    reply
    0
  • Cancelreply