我正在构建一个扩展include_path的自动加载器。它接受一个数组,附加explode()d include路径,删除对当前目录的所有引用,在数组开头添加一个当前目录,最后将整个内容连接()在一起,形成一个新的include路径。代码如下所示
<?php
static public function extendIncludePath (array $paths)
{
// Build a list of the current and new paths
$pathList = array_merge (explode (PATH_SEPARATOR, $paths), explode (PATH_SEPARATOR, get_include_path ()));
// Remove any references to the current directory from the path list
while ($key = array_search ('.', $pathList))
{
unset ($pathList [$key]);
}
// Put a current directory reference to the front of the path
array_unshift ($pathList, '.');
// Generate the new path list
$newPath = implode (PATH_SEPARATOR, $pathList);
if ($oldPath = set_include_path ($newPath))
{
self::$oldPaths [] = $oldPath;
}
return ($oldPath);
}
?>我还想在内爆数组之前在数组上使用array_unique(),这样如果有人不小心多次指定相同的路径,PHP就不会多次查找同一位置。但是,我还需要维护数组的排序顺序,因为include按照include路径中定义的顺序查找目录。我想首先查看当前目录,然后是我的搜索目录列表,最后是原始的包含路径,这样,例如,默认include_path中的一个公共库的旧版本不会包含在我的搜索列表中,而是包含在新版本的搜索列表中。
由于这些原因,我不能使用array_unique(),因为它对数组的内容进行排序。
有没有办法让array_unique保持数组中元素的顺序?
发布于 2011-03-18 17:29:11
没有直接使用array_unique();但是array_unique保留了键,所以您可以在以后执行ksort()来重新创建条目的原始顺序
发布于 2011-03-18 17:31:56
您也可以使用array_count_value。您将在函数结果的key处获得唯一的数组结果
它不会破坏您的数组排序内容。
发布于 2011-03-18 17:31:38
类似于:
$temp = array();
foreach ( $original_array as $value ) {
$temp[$value] = 1;
}
$original_array = array_keys($temp);https://stackoverflow.com/questions/5350080
复制相似问题