Indented list to multidimensional array

前端 未结 4 694
后悔当初
后悔当初 2020-12-06 08:21

I was surprised not to find an answer to this on SO (or elsewhere on the internet for that matter). It concerns a nested indented list which I want to convert into a multidi

4条回答
  •  猫巷女王i
    2020-12-06 09:13

    Am I the only one with a beautiful mind seeing the pattern?

    The input array is almost the same thing!, with the lines ending in only 3 possible ways: opening, whole, or closing parentheses.

    $L = 4;//estimate depth level
    
    function tabbed_text_to_array ($raw, $L) {
    
            $raw = preg_replace("/^(\\t*)([^\\t\\n]*)\\n?/m" ,  "\t$1'$2' => array(\n" , $raw );
    
        for( ; $L > 0 ; $L-- ) {
    
            for( $i=0; $i<3 ;$i++ ) {
                $preL = $L-1;
                $s = array( "^(\\t{{$L}})([^\\t\\),]*)(?=\\n\\t{{$L}}')", "^(\\t{{$L}})([^\\t\\),]*)(?=\\n(\\t{0,{$preL}})')", "^(\\t{{$L}})(\\),)(?=\\n(\\t{{$preL}})[^\t])" );
                $r = array(    "$1$2),"   ,     "$1$2)\n" . str_repeat("\t",$preL) . "),"    ,    "$1),\n$3),"    );
                $raw = preg_replace( "/$s[$i]/m" , $r[$i], $raw );
            }
        }
        return "array(\n". $raw. ")\n);";   
    
    }
    

    This function generates a string with a literal array. Then you just eval() it. It's not as bad as it looks. The double backslashes makes the reading harder, but it's simple.

    Like cell reproduction, it first adds in one pass the most common things: the quotation marks, commas and opening parentheses, and then it adds the smaller details in two more passes. All of them run once for each level you specify (You could waste code in finding out the deepest level to start processing from, but a guess is enough.)

    See the working demo / tool to convert tab-indented text into array

    Or visit a php fiddle with all the passes, so you can expand on this.

提交回复
热议问题