2013-12-11 75 views
1

问题:PHP数组 - 由阵列外部计算值排序(最高到最低)

我需要阵列(在它们出现的阵列内的顺序在符号列表中所示的内容)分类到左边数字的顺序(从最高到最低)。

这些数字对应于右侧目录路径中的分割数(它们不存储在当前数组中)。

我的问题出现了,因为我不知道如何使用示例中给出的值对数组进行排序 - 因为它们在数组之外。我尝试过使用多维数组,但是这只会导致更多的混淆!

由于代码在屏幕上输出列举如下:

  • 6#C:\程序文件(x86)\瓦帕\ WWW \规划器\进口\ homeworktasks
  • 5#C:\程序文件(x86)\ wamp \ www \ planner \ import
  • 7#C:\ Program Files(x86)\ Program Files(x86)\ wamp \ www \ planner \ import \ homeworktasks \ 11
  • 7# \ wamp \ www \ planner \ import \ homeworktasks \ 15
  • 7#C:\ Program Files(x86)\ wamp \ www \ planner \ import \ homeworktasks \ 17
  • 7#C:\ Program Files(x86)\ wamp \ www \ planner \ import \ homeworktasks \ 9
  • 7#C:\ Program Files(x86)\ wamp \ www \ planner \ import \ homeworktasks \ test
  • 8#C:\ Program Files文件(x86)\ wamp \ www \ planner \ import \ homeworktasks \ test \

代码:

<?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>"; 
} 
?> 
+1

把两个值放入数组,“多维”你叫它,确实是最简单的解决方案 - 那么你只需要一个小小的自写比较函数,你可以使用'usort',就完成了。 – CBroe

+0

数组的管理可能会随着您创建数组的方式而得到改进。你可以在你生成数组的地方显示代码吗? – James

+0

作为多维数组的替代方案,具有两个参数(计数和原始数组)的'array_multisort'自然也适用于此。这是一条线。 – Jon

回答

3

您可以使用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>'; 
} 
+0

是的,多数民众赞成在正确的方式:) – JustAPirate

1

你不需要MUL ti维数组。一个正常的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称为少了几分