Tetris-ing an array

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

    I would explode the values based on the / and then use array_intersect_assoc to detect the common elements and ensure they have the correct corresponding index in the array. The resulting array could be recombined to produce the common path.

    function getCommonPath($pathArray)
    {
        $pathElements = array();
    
        foreach($pathArray as $path)
        {
            $pathElements[] = explode("/",$path);
        }
    
        $commonPath = $pathElements[0];
    
        for($i=1;$i

    This is untested, but, the idea is that the $commonPath array only ever contains the elements of the path that have been contained in all path arrays that have been compared against it. When the loop is complete, we simply recombine it with / to get the true $commonPath

    Update As pointed out by Felix Kling, array_intersect won't consider paths that have common elements but in different orders... To solve this, I used array_intersect_assoc instead of array_intersect

    Update Added code to remove the common path (or tetris it!) from the array as well.

提交回复
热议问题