首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP数组-按数组外部计算的值排序(最高到最低)

PHP数组-按数组外部计算的值排序(最高到最低)
EN

Stack Overflow用户
提问于 2013-12-11 15:25:07
回答 2查看 412关注 0票数 1

问题:

我需要将数组(在项目符号列表中显示的内容按数组中出现的顺序排列)排序为左边数字的顺序(从最高到最低)。

这些数字对应于右侧目录路径中的分区数(它们目前没有存储在数组中.)。

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

由于下面列出的代码,在屏幕上的输出:

  • 6#C:\程序文件(X86)\wamp\www\planner\import\wamp工作任务
  • 5#C:\程序文件(x86)\wamp\www\planner\import
  • 7#C:\程序文件(x86)\wamp\www\planner\import\homeworktasks\11
  • 7#C:\程序文件(x86)\wamp\www\planner\import\homeworktasks\15
  • 7#C:\程序文件(x86)\wamp\www\planner\import\homeworktasks\17
  • 7#C:\程序文件(X86)\wamp\www\planner\导入\居家任务\9
  • 7#C:\程序文件(x86)\wamp\www\planner\import\homeworktasks\test
  • 8#C:\程序文件(x86)\wamp\www\planner\import\homeworktasks\test\inside

代码:

代码语言:javascript
运行
复制
<?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>";
}
?>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-11 15:50:52

您可以使用PHP的usort()函数。usort()“将使用用户提供的比较函数根据数组的值对数组进行排序”(PHP.net)

您必须编写一个可以比较两个值并返回-1、0或1的函数。

代码语言:javascript
运行
复制
<?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>';
}
票数 3
EN

Stack Overflow用户

发布于 2013-12-11 15:50:46

你不需要多维数组。普通的usort就能做到这一点。

代码语言:javascript
运行
复制
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被称为少一点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20523031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档