Tetris-ing an array

后端 未结 16 1734
时光取名叫无心
时光取名叫无心 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:20

    Well, there are already some solutions here but, just because it was fun:

    $values = array(
        '/www/htdocs/1/sites/lib/abcdedd',
        '/www/htdocs/1/sites/conf/xyz',
        '/www/htdocs/1/sites/conf/abc/def', 
        '/www/htdocs/1/sites/htdocs/xyz',
        '/www/htdocs/1/sites/lib2/abcdedd' 
    );
    
    function findCommon($values){
        $common = false;
        foreach($values as &$p){
            $p = explode('/', $p);
            if(!$common){
                $common = $p;
            } else {
                $common = array_intersect_assoc($common, $p);
            }
        }
        return $common;
    }
    function removeCommon($values, $common){
        foreach($values as &$p){
            $p = explode('/', $p);
            $p = array_diff_assoc($p, $common);
            $p = implode('/', $p);
        }
    
        return $values;
    }
    
    echo '
    ';
    print_r(removeCommon($values, findCommon($values)));
    echo '
    ';

    Output:

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

提交回复
热议问题