【问题标题】:PHP arrays - sorting (highest to lowest) by value calculated outside the arrayPHP数组 - 按数组外计算的值排序(从高到低)
【发布时间】:2013-12-29 15:44:26
【问题描述】:

问题:

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

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

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

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

  • 6 # C:\Program Files (x86)\wamp\www\planner\import\homeworktasks
  • 5 # C:\Program Files (x86)\wamp\www\planner\import
  • 7 # C:\Program Files (x86)\wamp\www\planner\import\homeworktasks\11
  • 7 # C:\Program Files (x86)\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\inside

代码:

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

【问题讨论】:

  • 将两个值放入数组中,正如你所说的“多维”,确实是最简单的解决方案——然后你只需要一个很小的自写比较函数,你可以使用 @ 987654322@,你就完成了。
  • 阵列的管理可能会通过您创建阵列的方式得到改进。你能显示你生成数组的代码吗?
  • 作为多维数组的替代方案,带有两个参数(计数数组和原始数组)的array_multisort 也可以自然地在这里工作。这是一条线。

标签: php arrays sorting directory


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您不需要多维数组。一个普通的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 被称为少一点

    【讨论】: