PHPfunctiontocreatestringchunksofincreasinglengths("fd6eg3"=>"f","fd","fd6","fd6eg3")

tl;dr: To store files under a path determined by their hash, I need a single function to get the following with level=3 and hash='fd6eg3': f/fd/fd6/fd6eg3

I am looking for a way to create chunks (of a given string) of increasing lengths, from the beginning of the string. Also, I want to limit the number of produced chunks.

The goal is to store a file named fd6eg3 under (with a number of chunks set to 3):

  • A directory named fd6.
  • Which is the child of a directory named fd.
  • Which is the child of a directory named f.

So the final path would be: f/fd/fd6/fd6eg3

The closest I got is getting the "directory part" (f/fd/fd6/) using the following function:

function computePathForHash(string $hash, int $level): string
{
    if ($level <= 0) {
        return '';
    } else {
        return computePathForHash($hash, $level - 1)
            . mb_substr($hash, 0, $level)
            . DIRECTORY_SEPARATOR
        ;
    }
}
echo computePathForHash('fd6eg3', 3);

Which output is resumed in this table:

level Returned
0 ""
1 "f/"
2 "f/fd/"
3 "f/fd/fd6/"

回答

我认为递归在适当的情况下很好,但是一个简单的for循环可以做到这一点,并且希望更易于维护。

只需循环到级别并每次添加哈希的起始块,然后在返回时添加完整的哈希......

function computePathForHash(string $hash, int $level): string
{
    $output = '';
    for ( $i = 1; $i <= $level; $i++ )  {
        $output .= mb_substr($hash, 0, $i) . DIRECTORY_SEPARATOR;
    }
    
    return $output . $hash;
}


以上是PHPfunctiontocreatestringchunksofincreasinglengths("fd6eg3"=&gt;"f","fd","fd6","fd6eg3")的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>