问题:
我需要将数组(在项目符号列表中显示的内容按数组中出现的顺序排列)排序为左边数字的顺序(从最高到最低)。
这些数字对应于右侧目录路径中的分区数(它们目前没有存储在数组中.)。
我的问题出现了,因为我不知道如何根据示例中给出的值对数组进行排序--因为它们在数组之外。我试着玩多维数组,但是这只会导致更多的混乱!
由于下面列出的代码,在屏幕上的输出:
代码:
<?php
//make all items in the array unique
$dir_list = array_unique($dir_list);
//create new array to sort into
$dir_list_sort = array();
//for each item in the array
foreach($dir_list as $dir)
{
//find depth of array
$dir_depth = substr_count($dir , DIRECTORY_SEPARATOR);
//stuff that is written to the page separated by a #
echo $dir_depth." # ".$dir."<br>";
}
?>发布于 2013-12-11 15:50:52
您可以使用PHP的usort()函数。usort()“将使用用户提供的比较函数根据数组的值对数组进行排序”(PHP.net)。
您必须编写一个可以比较两个值并返回-1、0或1的函数。
<?php
// This is just a shortcut for determining the directory depth
function dir_depth($directory_name)
{
return substr_count($directory_name, DIRECTORY_SEPARATOR);
}
// Takes two values ($a and $b) and returns either -1, 0 or 1
function compare($a, $b)
{
$depth_a = dir_depth($a);
$depth_b = dir_depth($b));
if ($depth_a == $depth_b) {
// If they have the same depth, return 0
return 0;
}
// If depth_a is smaller than depth_b, return -1; otherwise return 1
return ($depth_a < $depth_b) ? -1 : 1;
}
// Now we can sort the array.
// usort() needs two parameters:
// 1. the array that will be reordered
// 2. the name of the function that compares two values
usort($dir_list, 'compare');
// Now display the list
foreach ($dir_list as $dir) {
// here we can use our dir_depth() function again
echo dir_depth($dir) . ' # ' . $dir . '<br>';
}发布于 2013-12-11 15:50:46
你不需要多维数组。普通的usort就能做到这一点。
usort($dir_list, 'compareDirectoryDepth');
function compareDirectoryDepth($dir1, $dir2) {
$c1 = substr_count($dir1 , DIRECTORY_SEPARATOR);
$c2 = substr_count($dir2 , DIRECTORY_SEPARATOR);
return ($c1 == $c2 ? 0 : ($c1 < $c2 ? -1 : 1));
}当然,这可以稍微优化一下,所以substr_count被称为少一点。
https://stackoverflow.com/questions/20523031
复制相似问题