用PHP获取最深的文件路径
有没有人对如何从具有文件路径的数组中获取具有最深路径的元素有过绝妙的想法?如果这听起来很奇怪,请想象以下数组:用PHP获取最深的文件路径,php,arrays,path,Php,Arrays,Path,有没有人对如何从具有文件路径的数组中获取具有最深路径的元素有过绝妙的想法?如果这听起来很奇怪,请想象以下数组: /a/b /a /1/2/3/4 /1/2 /1/2/3/5 /a/b/c/d/e 我想得到的是: /1/2/3/4 /1/2/3/5 /a/b/c/d/e 想知道最快的方法是什么,而不必反复迭代整个数组。语言是PHP(5.2) 如果您可以保证“拼写”总是相同的(即:“/a/b c/d”与/a/b\/c/d),那么您应该能够进行一些简单的字符串比较,以查看其中一个字符串是否完全包含
/a/b
/a
/1/2/3/4
/1/2
/1/2/3/5
/a/b/c/d/e
我想得到的是:
/1/2/3/4
/1/2/3/5
/a/b/c/d/e
想知道最快的方法是什么,而不必反复迭代整个数组。语言是PHP(5.2) 如果您可以保证“拼写”总是相同的(即:“/a/b c/d”与/a/b\/c/d),那么您应该能够进行一些简单的字符串比较,以查看其中一个字符串是否完全包含在另一个字符串中。如果为真,则丢弃该字符串。 请注意,您需要在两个方向上进行比较
$aPathes = array(
'/a/b',
'/a',
'/1/2/3/4',
'/1/2',
'/1/2/3/5',
'/a/b/c/d/e'
);
function getDepth($sPath) {
return substr_count($sPath, '/');
}
$aPathDepths = array_map('getDepth', $aPathes);
arsort($aPathDepths);
foreach ($aPathDepths as $iKey => $iDepth) {
echo $aPathes[$iKey] . "\n";
}
另见
==更新===
$aUsed = array();
foreach ($aPathes as $sPath) {
foreach ($aUsed as $iIndex => $sUsed) {
if (substr($sUsed, 0, strlen($sPath)) == $sPath || substr($sPath, 0, strlen($sUsed)) == $sUsed) {
if (strlen($sUsed) < strlen($sPath)) {
array_splice($aUsed, $iIndex, 1);
$aUsed[] = $sPath;
}
continue 2;
}
}
$aUsed[] = $sPath;
}
$aUsed=array();
foreach($aPathes作为$sPath){
foreach($iIndex=>$sUsed){
如果(substr($sUsed,0,strlen($sPath))=$sPath | | substr($sPath,0,strlen($sUsed))=$sUsed){
if(strlen($sUsed)
另请参见。在您的说明之后,这里有一个函数可以实现这一点。它保存了一个找到的“最深路径”数组,并将每个路径与之进行比较。最佳情况是O(n)(如果所有路径都是最大路径的子路径),最坏情况是O(n2)(如果所有路径完全不同) 请注意,
continue 2
表示“在外循环上继续”
当你想要得到的结果有不同的深度时,你对“最深路径”的标准是什么?我一般不想找到最深的路径或第n个最深的路径,而是扔掉已经包含在其他路径中的路径。看看我的例子,了解我在追求什么。原因是我需要通过慢速FTP连接上传文件,并且必须在上传之前创建路径。如果我创建路径/some/very/deep/path,则无需检查/some/very或/some,因为如果/some/very/deep/path为,则保证它们在那里。:)
<?php
function getDeepestPaths($array)
{
$deepestPaths = array();
foreach ($array as $path)
{
$pathLength = strlen($path);
// look for all the paths we consider the longest
// (note how we're using references to the array members)
foreach ($deepestPaths as &$deepPath)
{
$deepPathLength = strlen($deepPath);
// if $path is prefixed by $deepPath, this means that $path is
// deeper, so we replace $deepPath with $path
if (substr($path, 0, $deepPathLength) == $deepPath)
{
$deepPath = $path;
continue 2;
}
// otherwise, if $deepPath is prefixed by $path, this means that
// $path is shallower; so we should stop looking
else if (substr($deepPath, 0, $pathLength) == $path)
{
continue 2;
}
}
// $path matches nothing currently in $deepestPaths, so we should
// add it to the array
$deepestPaths[] = $path;
}
return $deepestPaths;
}
$paths = array('/a/b', '/a', '/1/2/3/4', '/1/2', '/1/2/3/5', '/a/b/c/d/e');
print_r(getDeepestPaths($paths));
?>
if (substr($path, 0, $deepPathLength) == $deepPath && $path[$deepPathLength] == '/')
if (substr($deepPath, 0, $path) == $path && $deepPath[$path] == '/')