Multidimensional array from string

前端 未结 3 686
故里飘歌
故里飘歌 2020-12-11 21:52

Let\'s say I have this string which I want to put in a multidimensional array.

Edit : The number of subfolders in the string are dynamic .. from zero sub folders to

3条回答
  •  死守一世寂寞
    2020-12-11 22:19

    This can be solved recursively in another way by taking the items from the beginning of the array and when the last item is reached just return it.

    function make_tree( $arr ){
       if( count($arr) === 1){
          return array_pop( $arr );
       }else{
          $result[ array_shift( $arr )] = make_tree( $arr ) ; 
       }
       return $result;
    }
    
    $string  = "Folder1/Folder2/Folder3/filename1\n";
    $string .= "Folder1/Folder2/Folder3/filename2\n";
    $string .= "Folder4/Folder2/Folder3/filename3\n";
    
    $string = trim( $string );
    
    $files_paths = explode( PHP_EOL, $string);
    
    $result = [];
    
    foreach ($files_paths as $key => $value) {
       $parted = explode( '/', $value );
       $tree = make_tree( $parted );
       $result = array_merge_recursive( $result, $tree );
       
    }
    var_dump( $result );
    

提交回复
热议问题