Tetris-ing an array

后端 未结 16 1414
时光取名叫无心
时光取名叫无心 2021-01-30 15:38

Consider the following array:

/www/htdocs/1/sites/lib/abcdedd
/www/htdocs/1/sites/conf/xyz
/www/htdocs/1/sites/conf/abc/         


        
16条回答
  •  难免孤独
    2021-01-30 16:22

    A naive approach would be to explode the paths at the / and successive compare every element in the arrays. So e.g. the first element would be empty in all arrays, so it will be removed, the next element will be www, it is the same in all arrays, so it gets removed, etc.

    Something like (untested)

    $exploded_paths = array();
    
    foreach($paths as $path) {
        $exploded_paths[] = explode('/', $path);
    }
    
    $equal = true;
    $ref = &$exploded_paths[0]; // compare against the first path for simplicity
    
    while($equal) {   
        foreach($exploded_paths as $path_parts) {
            if($path_parts[0] !== $ref[0]) {
                $equal = false;
                break;
            }
        }
        if($equal) {
            foreach($exploded_paths as &$path_parts) {
                array_shift($path_parts); // remove the first element
            }
        }
    }
    

    Afterwards you just have to implode the elements in $exploded_paths again:

    function impl($arr) {
        return '/' . implode('/', $arr);
    }
    $paths = array_map('impl', $exploded_paths);
    

    Which gives me:

    Array
    (
        [0] => /lib/abcdedd
        [1] => /conf/xyz
        [2] => /conf/abc/def
        [3] => /htdocs/xyz
        [4] => /conf/xyz
    )
    

    This might not scale well ;)

提交回复
热议问题