如何在PHP中对数组和数据进行排序?

发布于 2025-01-19 10:30:43 字数 676 浏览 5 评论 0 原文

这个问题旨在作为有关在PHP中排序数组的问题的参考。很容易想到您的特殊情况是独一无二的,值得一个新问题,但实际上大多数是此页面上一种解决方案的较小变体。

如果您的问题是作为此副本的重复,请要求重新打开您的问题,如果您可以解释为什么它与以下所有内容有明显不同。

我该如何在PHP中分类数组?
我如何在php中排序复杂数组?
如何在PHP中对对象进行排序?


  1. 基本的一维数组;包括。多维阵列,包括。对象的数组;包括。根据另一个数组对一个数组进行排序

  2. 与Spl

    分类
  3. 稳定排序

用于使用PHP的现有功能的实际答案,请参见1.,有关分类算法的学术上的信息答案(哪个PHP的功能)实施以及您可能需要的真正非常复杂的情况),请参阅2。

This question is intended as a reference for questions about sorting arrays in PHP. It is easy to think that your particular case is unique and worthy of a new question, but most are actually minor variations of one of the solutions on this page.

If your question is closed as a duplicate of this one, please ask for your question to be reopened only if you can explain why it differs markedly from all of the below.

How do I sort an array in PHP?
How do I sort a complex array in PHP?
How do I sort an array of objects in PHP?


  1. Basic one-dimensional arrays; Incl. Multidimensional arrays, incl. arrays of objects; Incl. Sorting one array based on another

  2. Sorting with SPL

  3. Stable sort

For the practical answer using PHP's existing functions see 1., for the academic in-detail answer on sorting algorithms (which PHP's functions implement and which you may need for really, really complex cases), see 2.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

Bonjour°[大白 2025-01-26 10:30:43

基本一维数组

$array = array(3, 5, 2, 8);

适用的排序功能:

  • sort
  • rsort
  • asort
  • arsort
  • natsort
  • <代码> natcasesort
  • ksort
  • krsort

这些之间的区别仅仅是保留键值关联(“ a ”功能),无论是低对高还是反向(“ r ”),无论是对值还是键(“ k ”),以及如何比较值(“ nat “与正常人)。参见 http://php.net/manual/manual/aray/array.sorting.php 有关概述并链接到更多详细信息。

多维数组,包括对象的数组,

$array = array(
    array('foo' => 'bar', 'baz' => 42),
    array('foo' => ...,   'baz' => ...),
    ...
);

如果要按每个条目的键'foo'对 $ array 进行排序,则需要自定义比较函数。上面的 sort 和相关功能在他们知道如何比较和排序的简单值上工作。 PHP不仅要“知道”如何使用复杂值喜欢 array('foo'=&gt;'bar','baz'=&gt; 42)虽然;因此,您需要告诉它。

为此,您需要创建一个比较函数。该功能需要两个元素,并且必须返回 0 如果这些元素被认为是相等的,则值低于 0 ,如果第一个值较低,并且值高于 0 如果第一个值更高。这就是所有需要的:

function cmp(array $a, array $b) {
    if ($a['foo'] < $b['foo']) {
        return -1;
    } else if ($a['foo'] > $b['foo']) {
        return 1;
    } else {
        return 0;
    }
}

通常,您将需要使用匿名函数打回来。如果要使用方法或静态方法,请参见其他指定调用的方法在PHP 中。

然后,您使用以下功能之一:

再次,它们仅在保持键值关联并按值或键进行排序方面有所不同。阅读他们的文档以获取详细信息。

示例用法:

usort($array, 'cmp');

用户将从数组中获取两个项目,并与它们调用您的 cmp 函数。因此, cmp()将以 $ a array('foo'=&gt;'bar','baz'=&gt; 42) $ b 作为另一个 array('foo'=&gt; ...,'baz'=&gt; ...)。然后,该函数返回到用户哪个值更大或它们是否相等。 用户重复此过程,传递 $ a $ b 的不同值,直到对数组进行排序。 cmp 函数将被称为多次,至少 $ array 中的值一样多次,具有不同的值组合的值组合代码> $ a $ b 每次。

要习惯这个想法,请尝试以下操作:

function cmp($a, $b) {
    echo 'cmp called with $a:', PHP_EOL;
    var_dump($a);
    echo 'and $b:', PHP_EOL;
    var_dump($b);
}

您所做的只是定义一种比较两个项目的自定义方法,这就是您所需要的。这可以与各种价值观一起使用。

顺便说一句,这对任何值都起作用,这些值不必是复杂的数组。如果您有自定义比较,也可以在简单的数字阵列上进行。

sort 通过参考和不返回任何有用的东西!

请注意,阵列中的到位,您无需将返回值分配给任何内容。 $ array = sort($ array)将用 true 替换数组,而不是用排序的数组。只是 sort($ array); 工作。

自定义数字比较

如果要按 baz 键进行排序,这是数字的,您需要做的就是:

function cmp(array $a, array $b) {
    return $a['baz'] - $b['baz'];
}

感谢 Math的功能,这将返回一个值&lt; 0,0或&gt; 0取决于 $ a 等于还是大于 $ b

请注意,这对于 float 值无法正常工作,因为它们将被简化为 int 并丢失精度。使用显式 -1 ,<代码> 0 和 1 返回值。

对象

如果您有一系列对象,则其工作方式相同:

function cmp($a, $b) {
    return $a->baz - $b->baz;
}

功能

您可以在比较功能中执行任何需要的操作,包括调用函数:

function cmp(array $a, array $b) {
    return someFunction($a['baz']) - someFunction($b['baz']);
}

字符串的

第一个字符串比较版本的快捷方式:

function cmp(array $a, array $b) {
    return strcmp($a['foo'], $b['foo']);
}

strcmp dik确切地说, cmp 在这里,它返回 -1 0 1

太空飞船运营商

PHP 7引入了 SpaceShip Operator ,该 ,该可以简化和简化相等/较小/​​更小的类型:

function cmp(array $a, array $b) {
    return $a['foo'] <=> $b['foo'];
}

通过多个类型进行比较 :字段

如果您要主要按 foo 进行排序,但是如果 foo 对两个元素等于 baz

function cmp(array $a, array $b) {
    if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
        return $cmp;
    } else {
        return $a['baz'] - $b['baz'];
    }
}

对于那些熟悉的人,这是等效的使用订单的SQL查询,Baz
另请参阅这个非常整洁的速记版本如何为任意数量的密钥动态创建这样的比较函数

请分类为静态顺序

如果您想将元素分类为“手动订单”,例如 “ foo”,“ bar”,“ baz”

function cmp(array $a, array $b) {
    static $order = array('foo', 'bar', 'baz');
    return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}

对于上述所有内容, 5.3或更高版本(您确实应该),使用匿名函数来较短的代码,并避免使另一个全局函数浮动:

usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });

这就是简单地对复杂的多维数组进行排序。同样,只要根据教授PHP如何判断两个项目中的哪个是“更大” 的话;让PHP进行实际分类。

同样,对于上述所有内容,要在上升和降序之间切换,只需交换 $ a $ b 参数周围。例如:

return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending

根据另一个数组对一个数组进行排序

,然后有特殊的 array_multisort ,它让您允许您根据另一个数组对一个数组进行排序:

$array1 = array( 4,   6,   1);
$array2 = array('a', 'b', 'c');

这里的预期结果将是:

$array2 = array('c', 'a', 'b');  // the sorted order of $array1

使用 array_multisort 到达那里:

array_multisort($array1, $array2);

截至PHP 5.5.0,您可以使用 array_column 从一个多维数组并在该列上对数组进行排序:

array_multisort(array_column($array, 'foo'), SORT_DESC, $array);

您还可以在任一方向上分类多个列:

array_multisort(array_column($array, 'foo'), SORT_DESC,
                array_column($array, 'bar'), SORT_ASC,
                $array);

从PHP 7.0.0开始,您也可以从对象数组中提取属性。


如果您有更多常见的情况,请随时编辑此答案。

Basic one dimensional arrays

$array = array(3, 5, 2, 8);

Applicable sort functions:

  • sort
  • rsort
  • asort
  • arsort
  • natsort
  • natcasesort
  • ksort
  • krsort

The difference between those is merely whether key-value associations are kept (the "a" functions), whether it sorts low-to-high or reverse ("r"), whether it sorts values or keys ("k") and how it compares values ("nat" vs. normal). See http://php.net/manual/en/array.sorting.php for an overview and links to further details.

Multi dimensional arrays, including arrays of objects

$array = array(
    array('foo' => 'bar', 'baz' => 42),
    array('foo' => ...,   'baz' => ...),
    ...
);

If you want to sort $array by the key 'foo' of each entry, you need a custom comparison function. The above sort and related functions work on simple values that they know how to compare and sort. PHP does not simply "know" what to do with a complex value like array('foo' => 'bar', 'baz' => 42) though; so you need to tell it.

To do that, you need to create a comparison function. That function takes two elements and must return 0 if these elements are considered equal, a value lower than 0 if the first value is lower and a value higher than 0 if the first value is higher. That's all that's needed:

function cmp(array $a, array $b) {
    if ($a['foo'] < $b['foo']) {
        return -1;
    } else if ($a['foo'] > $b['foo']) {
        return 1;
    } else {
        return 0;
    }
}

Often, you will want to use an anonymous function as the callback. If you want to use a method or static method, see the other ways of specifying a callback in PHP.

You then use one of these functions:

Again, they only differ in whether they keep key-value associations and sort by values or keys. Read their documentation for details.

Example usage:

usort($array, 'cmp');

usort will take two items from the array and call your cmp function with them. So cmp() will be called with $a as array('foo' => 'bar', 'baz' => 42) and $b as another array('foo' => ..., 'baz' => ...). The function then returns to usort which of the values was larger or whether they were equal. usort repeats this process passing different values for $a and $b until the array is sorted. The cmp function will be called many times, at least as many times as there are values in $array, with different combinations of values for $a and $b every time.

To get used to this idea, try this:

function cmp($a, $b) {
    echo 'cmp called with $a:', PHP_EOL;
    var_dump($a);
    echo 'and $b:', PHP_EOL;
    var_dump($b);
}

All you did was define a custom way to compare two items, that's all you need. That works with all sorts of values.

By the way, this works on any value, the values don't have to be complex arrays. If you have a custom comparison you want to do, you can do it on a simple array of numbers too.

sort sorts by reference and does not return anything useful!

Note that the array sorts in place, you do not need to assign the return value to anything. $array = sort($array) will replace the array with true, not with a sorted array. Just sort($array); works.

Custom numeric comparisons

If you want to sort by the baz key, which is numeric, all you need to do is:

function cmp(array $a, array $b) {
    return $a['baz'] - $b['baz'];
}

Thanks to The PoWEr oF MATH this returns a value < 0, 0 or > 0 depending on whether $a is lower than, equal to or larger than $b.

Note that this won't work well for float values, since they'll be reduced to an int and lose precision. Use explicit -1, 0 and 1 return values instead.

Objects

If you have an array of objects, it works the same way:

function cmp($a, $b) {
    return $a->baz - $b->baz;
}

Functions

You can do anything you need inside a comparison function, including calling functions:

function cmp(array $a, array $b) {
    return someFunction($a['baz']) - someFunction($b['baz']);
}

Strings

A shortcut for the first string comparison version:

function cmp(array $a, array $b) {
    return strcmp($a['foo'], $b['foo']);
}

strcmp does exactly what's expected of cmp here, it returns -1, 0 or 1.

Spaceship operator

PHP 7 introduced the spaceship operator, which unifies and simplifies equal/smaller/larger than comparisons across types:

function cmp(array $a, array $b) {
    return $a['foo'] <=> $b['foo'];
}

Sorting by multiple fields

If you want to sort primarily by foo, but if foo is equal for two elements sort by baz:

function cmp(array $a, array $b) {
    if (($cmp = strcmp($a['foo'], $b['foo'])) !== 0) {
        return $cmp;
    } else {
        return $a['baz'] - $b['baz'];
    }
}

For those familiar, this is equivalent to an SQL query with ORDER BY foo, baz.
Also see this very neat shorthand version and how to create such a comparison function dynamically for an arbitrary number of keys.

Sorting into a manual, static order

If you want to sort elements into a "manual order" like "foo", "bar", "baz":

function cmp(array $a, array $b) {
    static $order = array('foo', 'bar', 'baz');
    return array_search($a['foo'], $order) - array_search($b['foo'], $order);
}

For all the above, if you're using PHP 5.3 or higher (and you really should), use anonymous functions for shorter code and to avoid having another global function floating around:

usort($array, function (array $a, array $b) { return $a['baz'] - $b['baz']; });

That's how simple sorting a complex multi-dimensional array can be. Again, just think in terms of teaching PHP how to tell which of two items is "greater"; let PHP do the actual sorting.

Also for all of the above, to switch between ascending and descending order simply swap the $a and $b arguments around. E.g.:

return $a['baz'] - $b['baz']; // ascending
return $b['baz'] - $a['baz']; // descending

Sorting one array based on another

And then there's the peculiar array_multisort, which lets you sort one array based on another:

$array1 = array( 4,   6,   1);
$array2 = array('a', 'b', 'c');

The expected result here would be:

$array2 = array('c', 'a', 'b');  // the sorted order of $array1

Use array_multisort to get there:

array_multisort($array1, $array2);

As of PHP 5.5.0 you can use array_column to extract a column from a multi dimensional array and sort the array on that column:

array_multisort(array_column($array, 'foo'), SORT_DESC, $array);

You can also sort on more than one column each in either direction:

array_multisort(array_column($array, 'foo'), SORT_DESC,
                array_column($array, 'bar'), SORT_ASC,
                $array);

As of PHP 7.0.0 you can also extract properties from an array of objects.


If you have more common cases, feel free to edit this answer.

已下线请稍等 2025-01-26 10:30:43

大多数基本方法已经被 deveze 我会尝试

以Spl

splheap

class SimpleHeapSort extends SplHeap {
    public function compare($a, $b) {
        return strcmp($a, $b);
    }
}

// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");

echo implode(PHP_EOL, iterator_to_array($heap));

output

c
b
a

splmaxheap

splmaxheap类提供了堆的主要功能,使最大程度地保持在顶部。

$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);

splminheap

splminheap类提供堆的主要功能,将最小值保持在顶部。

$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);

其他类型的排序

气泡排序

来自 wikipedia on Bubble Sort:

气泡排序,有时被错误地称为沉没排序,是一种简单的排序算法,通过反复踏入列表以进行排序,比较每对相邻的项目并将它们交换为错误的顺序。通过列表重复列表,直到不需要交换为止,这表明列表已排序。该算法从较小的元素“气泡”到列表的顶部获取其名称。因为它仅使用比较来在元素上运行,所以这是一种比较。尽管该算法很简单,但大多数其他排序算法对于大列表更有效。

function bubbleSort(array $array) {
    $array_size = count($array);
    for($i = 0; $i < $array_size; $i ++) {
        for($j = 0; $j < $array_size; $j ++) {
            if ($array[$i] < $array[$j]) {
                $tem = $array[$i];
                $array[$i] = $array[$j];
                $array[$j] = $tem;
            }
        }
    }
    return $array;
}

选择排序

来自 wikipedia on Selection Sorts上的文章:

在计算机科学中,选择排序是一种分类算法,特别是现场比较。它具有O(n2)时间复杂性,使其在大列表上效率低下,并且通常比类似的插入排序更糟。选择排序以其简单性而闻名,并且在某些情况下具有比更复杂算法的性能优势,尤其是在辅助内存受到限制的情况下。

function selectionSort(array $array) {
    $length = count($array);
    for($i = 0; $i < $length; $i ++) {
        $min = $i;
        for($j = $i + 1; $j < $length; $j ++) {
            if ($array[$j] < $array[$min]) {
                $min = $j;
            }
        }
        $tmp = $array[$min];
        $array[$min] = $array[$i];
        $array[$i] = $tmp;
    }
    return $array;
}

插入

wikipedia文章上的文章:

插入排序是一种简单的排序算法,一次构建最终排序的数组(或列表)一次。在大型列表中,它的效率要比更高级的算法(例如QuickSort,heapsort或Merge Sorts)少得多。但是,插入排序提供了几个优点:

function insertionSort(array $array) {
    $count = count($array);
    for($i = 1; $i < $count; $i ++) {

        $j = $i - 1;
        // second element of the array
        $element = $array[$i];
        while ( $j >= 0 && $array[$j] > $element ) {
            $array[$j + 1] = $array[$j];
            $array[$j] = $element;
            $j = $j - 1;
        }
    }
    return $array;
}

shellsort

来自 shellsort上的wikipedia文章:

Shellsort,也称为Shell Sort或Shell的方法,是现场比较。它通过启动与元素的比较和交换元素在使用相邻元素之前的元素进行比较和交换,从而概括了交换排序,例如插入或气泡排序。

function shellSort(array $array) {
    $gaps = array(
            1,
            2,
            3,
            4,
            6
    );
    $gap = array_pop($gaps);
    $length = count($array);
    while ( $gap > 0 ) {
        for($i = $gap; $i < $length; $i ++) {
            $tmp = $array[$i];
            $j = $i;
            while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
                $array[$j] = $array[$j - $gap];
                $j -= $gap;
            }
            $array[$j] = $tmp;
        }
        $gap = array_pop($gaps);
    }
    return $array;
}

梳子排序

来自 wikipedia在梳子上的文章:

梳子排序是一种相对简单的排序算法,最初由Wlodzimierz dobosiewicz于1980年设计。后来,它由Stephen Lacey和Richard Box在1991年重新发现。梳子排序改进了泡泡排序。

>

>

function combSort(array $array) {
    $gap = count($array);
    $swap = true;
    while ( $gap > 1 || $swap ) {
        if ($gap > 1)
            $gap /= 1.25;
        $swap = false;
        $i = 0;
        while ( $i + $gap < count($array) ) {
            if ($array[$i] > $array[$i + $gap]) {
                // swapping the elements.
                list($array[$i], $array[$i + $gap]) = array(
                        $array[$i + $gap],
                        $array[$i]
                );
                $swap = true;
            }
            $i ++;
        }
    }
    return $array;
}

合并

Merge Sort上的Wikipedia文章:

在计算机科学中,合并排序(通常也是拼写的Mergesort)是O(n log n)基于比较的分类算法。大多数实现都会产生稳定的排序,这意味着该实现保留了排序输出中均等元素的输入顺序

function mergeSort(array $array) {
    if (count($array) <= 1)
        return $array;

    $left = mergeSort(array_splice($array, floor(count($array) / 2)));
    $right = mergeSort($array);

    $result = array();

    while ( count($left) > 0 && count($right) > 0 ) {
        if ($left[0] <= $right[0]) {
            array_push($result, array_shift($left));
        } else {
            array_push($result, array_shift($right));
        }
    }
    while ( count($left) > 0 )
        array_push($result, array_shift($left));

    while ( count($right) > 0 )
        array_push($result, array_shift($right));

    return $result;
}

大多数实现都会产生稳定的形式,这意味着该实现从

QuickSort或分区交换排序是由Tony Hoare开发的一种排序算法,平均而言,O(n log n)比较n个项目。在最坏的情况下,它可以进行o(n2)比较,尽管这种行为很少。

function quickSort(array $array) {
    if (count($array) == 0) {
        return $array;
    }
    $pivot = $array[0];
    $left = $right = array();
    for($i = 1; $i < count($array); $i ++) {
        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }
    }
    return array_merge(quickSort($left), array(
            $pivot
    ), quickSort($right));
}

置换

wikipedia on repuren -noting sort:

排列排序,通过生成输入数组/列表的可能排列进行进行进行进行,直到发现排序。

function permutationSort($items, $perms = array()) {
    if (empty($items)) {
        if (inOrder($perms)) {
            return $perms;
        }
    } else {
        for($i = count($items) - 1; $i >= 0; -- $i) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            $res = permutationSort($newitems, $newperms);
            if ($res) {
                return $res;
            }
        }
    }
}

function inOrder($array) {
    for($i = 0; $i < count($array); $i ++) {
        if (isset($array[$i + 1])) {
            if ($array[$i] > $array[$i + 1]) {
                return False;
            }
        }
    }
    return True;
}

radix

radix sort上的wikipedia文章:

在计算机科学中,radix Sort是一种非复杂整数排序算法,它通过按键按键按单个数字分组,它们具有相同的显着位置和值。

// Radix Sort for 0 to 256
function radixSort($array) {
    $n = count($array);
    $partition = array();

    for($slot = 0; $slot < 256; ++ $slot) {
        $partition[] = array();
    }

    for($i = 0; $i < $n; ++ $i) {
        $partition[$array[$i]->age & 0xFF][] = &$array[$i];
    }

    $i = 0;

    for($slot = 0; $slot < 256; ++ $slot) {
        for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
            $array[$i ++] = &$partition[$slot][$j];
        }
    }
    return $array;
}

Well most basic methods are already covered by deceze I would try to look at other types of sort

Sorting with SPL

SplHeap

class SimpleHeapSort extends SplHeap {
    public function compare($a, $b) {
        return strcmp($a, $b);
    }
}

// Let's populate our heap here (data of 2009)
$heap = new SimpleHeapSort();
$heap->insert("a");
$heap->insert("b");
$heap->insert("c");

echo implode(PHP_EOL, iterator_to_array($heap));

Output

c
b
a

SplMaxHeap

The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

$heap = new SplMaxHeap();
$heap->insert(1);
$heap->insert(2);
$heap->insert(3);

SplMinHeap

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

$heap = new SplMinHeap ();
$heap->insert(3);
$heap->insert(1);
$heap->insert(2);

Other Types of Sort

Bubble Sort

From the Wikipedia article on Bubble Sort:

Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.

function bubbleSort(array $array) {
    $array_size = count($array);
    for($i = 0; $i < $array_size; $i ++) {
        for($j = 0; $j < $array_size; $j ++) {
            if ($array[$i] < $array[$j]) {
                $tem = $array[$i];
                $array[$i] = $array[$j];
                $array[$j] = $tem;
            }
        }
    }
    return $array;
}

Selection sort

From the Wikipedia article on Selection sort:

In computer science, selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

function selectionSort(array $array) {
    $length = count($array);
    for($i = 0; $i < $length; $i ++) {
        $min = $i;
        for($j = $i + 1; $j < $length; $j ++) {
            if ($array[$j] < $array[$min]) {
                $min = $j;
            }
        }
        $tmp = $array[$min];
        $array[$min] = $array[$i];
        $array[$i] = $tmp;
    }
    return $array;
}

Insertion sort

From the Wikipedia article on Insertion sort:

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:

function insertionSort(array $array) {
    $count = count($array);
    for($i = 1; $i < $count; $i ++) {

        $j = $i - 1;
        // second element of the array
        $element = $array[$i];
        while ( $j >= 0 && $array[$j] > $element ) {
            $array[$j + 1] = $array[$j];
            $array[$j] = $element;
            $j = $j - 1;
        }
    }
    return $array;
}

Shellsort

From the Wikipedia article on Shellsort:

Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It generalizes an exchanging sort, such as insertion or bubble sort, by starting the comparison and exchange of elements with elements that are far apart before finishing with neighboring elements.

function shellSort(array $array) {
    $gaps = array(
            1,
            2,
            3,
            4,
            6
    );
    $gap = array_pop($gaps);
    $length = count($array);
    while ( $gap > 0 ) {
        for($i = $gap; $i < $length; $i ++) {
            $tmp = $array[$i];
            $j = $i;
            while ( $j >= $gap && $array[$j - $gap] > $tmp ) {
                $array[$j] = $array[$j - $gap];
                $j -= $gap;
            }
            $array[$j] = $tmp;
        }
        $gap = array_pop($gaps);
    }
    return $array;
}

Comb sort

From the Wikipedia article on Comb sort:

Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.

function combSort(array $array) {
    $gap = count($array);
    $swap = true;
    while ( $gap > 1 || $swap ) {
        if ($gap > 1)
            $gap /= 1.25;
        $swap = false;
        $i = 0;
        while ( $i + $gap < count($array) ) {
            if ($array[$i] > $array[$i + $gap]) {
                // swapping the elements.
                list($array[$i], $array[$i + $gap]) = array(
                        $array[$i + $gap],
                        $array[$i]
                );
                $swap = true;
            }
            $i ++;
        }
    }
    return $array;
}

Merge sort

From the Wikipedia article on Merge sort:

In computer science, a merge sort (also commonly spelled mergesort) is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output

function mergeSort(array $array) {
    if (count($array) <= 1)
        return $array;

    $left = mergeSort(array_splice($array, floor(count($array) / 2)));
    $right = mergeSort($array);

    $result = array();

    while ( count($left) > 0 && count($right) > 0 ) {
        if ($left[0] <= $right[0]) {
            array_push($result, array_shift($left));
        } else {
            array_push($result, array_shift($right));
        }
    }
    while ( count($left) > 0 )
        array_push($result, array_shift($left));

    while ( count($right) > 0 )
        array_push($result, array_shift($right));

    return $result;
}

Quicksort

From the Wikipedia article on Quicksort:

Quicksort, or partition-exchange sort, is a sorting algorithm developed by Tony Hoare that, on average, makes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare.

function quickSort(array $array) {
    if (count($array) == 0) {
        return $array;
    }
    $pivot = $array[0];
    $left = $right = array();
    for($i = 1; $i < count($array); $i ++) {
        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }
    }
    return array_merge(quickSort($left), array(
            $pivot
    ), quickSort($right));
}

Permutation sort

From the Wikipedia article on Permutation sort:

Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one.

function permutationSort($items, $perms = array()) {
    if (empty($items)) {
        if (inOrder($perms)) {
            return $perms;
        }
    } else {
        for($i = count($items) - 1; $i >= 0; -- $i) {
            $newitems = $items;
            $newperms = $perms;
            list($foo) = array_splice($newitems, $i, 1);
            array_unshift($newperms, $foo);
            $res = permutationSort($newitems, $newperms);
            if ($res) {
                return $res;
            }
        }
    }
}

function inOrder($array) {
    for($i = 0; $i < count($array); $i ++) {
        if (isset($array[$i + 1])) {
            if ($array[$i] > $array[$i + 1]) {
                return False;
            }
        }
    }
    return True;
}

Radix sort

From the Wikipedia article on Radix sort:

In computer science, radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.

// Radix Sort for 0 to 256
function radixSort($array) {
    $n = count($array);
    $partition = array();

    for($slot = 0; $slot < 256; ++ $slot) {
        $partition[] = array();
    }

    for($i = 0; $i < $n; ++ $i) {
        $partition[$array[$i]->age & 0xFF][] = &$array[$i];
    }

    $i = 0;

    for($slot = 0; $slot < 256; ++ $slot) {
        for($j = 0, $n = count($partition[$slot]); $j < $n; ++ $j) {
            $array[$i ++] = &$partition[$slot][$j];
        }
    }
    return $array;
}
叫嚣ゝ 2025-01-26 10:30:43

稳定排序

假设您有一个像这样的数组:

['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']

现在您只想对第一个字母进行排序:

usort($array, function($a, $b) {
    return strcmp($a[0], $b[0]);
});

结果是这样的:

['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']

排序不稳定!

敏锐的观察者可能已经注意到,数组排序算法 (QuickSort) 无法产生稳定的结果,并且具有相同首字母的单词之间的原始顺序未保留。这种情况很简单,我们应该比较整个字符串,但我们假设您的用例更复杂,例如不同字段上的两次连续排序不应抵消彼此的工作。

施瓦茨变换

施瓦茨变换,也称为装饰- sort-undecorate 习语,通过本质上不稳定的排序算法实现稳定的排序。

首先,用另一个包含主键(值)和辅助键(其索引或位置)的数组来装饰每个数组元素:

array_walk($array, function(&$element, $index) {
    $element = array($element, $index); // decorate
});

这会将数组转换为:

[
    ['Kale', 0], ['Kaleidoscope', 1], 
    ['Aardvark', 2], ['Apple', 3], 
    ['Leicester', 4], ['Lovely', 5]
]

现在,我们调整比较步骤;我们再次比较第一个字母,如果相同,则使用辅助键来保留原始顺序:

usort($array, function($a, $b) {
    // $a[0] and $b[0] contain the primary sort key
    // $a[1] and $b[1] contain the secondary sort key
    $tmp = strcmp($a[0][0], $b[0][0]);

    if ($tmp != 0) {
        return $tmp; // use primary key comparison results
    }

    return $a[1] - $b[1]; // use secondary key
});

然后,我们取消修饰:

array_walk($array, function(&$element) {
    $element = $element[0];
});

最终结果:

['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']

重用怎么样?

你必须重写用于处理转换后的数组元素的比较函数;您可能不想编辑精致的比较函数,因此这里是比较函数的包装:

function stablecmp($fn)
{
    return function($a, $b) use ($fn) {
        if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
            return $tmp;
        } else {
            return $a[1] - $b[1];
        }
    };
}

让我们使用此函数编写排序步骤:

usort($array, stablecmp(function($a, $b) {
    return strcmp($a[0], $b[0]);
}));

瞧!您的原始比较代码又回来了。

Stable sort

Let's say you have an array like this:

['Kale', 'Kaleidoscope', 'Aardvark', 'Apple', 'Leicester', 'Lovely']

And now you want to sort on the first letter only:

usort($array, function($a, $b) {
    return strcmp($a[0], $b[0]);
});

The outcome is this:

['Apple', 'Aardvark', 'Kale', 'Kaleidoscope', 'Lovely', 'Leicester']

The sort wasn't stable!

The keen observer may have noticed that the array sorting algorithm (QuickSort) didn't produce a stable outcome and that the original order between words of the same first letter wasn't preserved. This case is trivial and we should have compared the whole string, but let's assume your use-case is more complicated, such as two consecutive sorts on different fields that shouldn't cancel out each other's work.

The Schwartzian transform

The Schwartzian transform, also referred to as the decorate-sort-undecorate idiom, effects a stable sort with an inherently unstable sorting algorithm.

First, you decorate each array element with another array comprising a primary key (the value) and a secondary key (its index or position):

array_walk($array, function(&$element, $index) {
    $element = array($element, $index); // decorate
});

This transforms the array into this:

[
    ['Kale', 0], ['Kaleidoscope', 1], 
    ['Aardvark', 2], ['Apple', 3], 
    ['Leicester', 4], ['Lovely', 5]
]

Now, we adjust the comparison step; we compare the first letter again, but if they're the same, the secondary key is used to retain the original ordering:

usort($array, function($a, $b) {
    // $a[0] and $b[0] contain the primary sort key
    // $a[1] and $b[1] contain the secondary sort key
    $tmp = strcmp($a[0][0], $b[0][0]);

    if ($tmp != 0) {
        return $tmp; // use primary key comparison results
    }

    return $a[1] - $b[1]; // use secondary key
});

Afterwards, we undecorate:

array_walk($array, function(&$element) {
    $element = $element[0];
});

The final result:

['Aardvark', 'Apple', 'Kale', 'Kaleidoscope', 'Leicester', 'Lovely']

What about reuse?

You had to rewrite your comparison function to work with the transformed array elements; you may not want to edit your delicate comparison functions, so here's a wrapper for the comparison function:

function stablecmp($fn)
{
    return function($a, $b) use ($fn) {
        if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
            return $tmp;
        } else {
            return $a[1] - $b[1];
        }
    };
}

Let's write the sort step using this function:

usort($array, stablecmp(function($a, $b) {
    return strcmp($a[0], $b[0]);
}));

Voila! Your pristine comparison code is back.

挽容 2025-01-26 10:30:43

从带有闭包的 PHP 5.3 开始,还可以使用闭包来确定排序顺序。

例如,假设 $array 是包含月份属性的对象数组。

 $orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");

 usort($array, function($a, $b) use ($orderArray){
       return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
 }); 

As of PHP 5.3 with closures it is also possible to use a closure to determine the order of your sort.

For example assuming $array is an array of objects that contain a month property.

 $orderArray = array("Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");

 usort($array, function($a, $b) use ($orderArray){
       return array_search($a->month, $orderArray) - array_search($b->month, $orderArray);
 }); 
遗弃M 2025-01-26 10:30:43

linq

in .NET,LINQ经常用于排序,它在比较函数上提供了更好的语法,尤其是当需要通过多个字段对对象进行排序时。 LINQ的几个端口都到PHP,包括 yalinqo library*。有了它,可以用一条线对数组进行排序,而无需编写复杂的比较功能。

$sortedByName         = from($objects)->orderBy('$v->name');
$sortedByCount        = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');

可以通过将回调作为第二个参数来进一步定制比较,例如:

$sortedByFilenameNat  = from($objects)->orderBy('$v->filename', 'strnatcmp');

'$ v-&gt; count' function($ v){返回$ v的速记 - &gt; count; } (可以使用任何一种)。这些方法链返回迭代器,可以通过在需要时添加 - &gt; toarray()将迭代器转换为数组。

内部, orderby 和相关方法调用适当的数组排序函数( uasort krsort Multisort usort 等)。

LINQ包含更多受SQL启发的方法:过滤,分组,加入,汇总等。它最适合在不依赖数据库的情况下需要执行数组和对象的复杂转换的情况。

*由我开发的,请参见Readme,以获取更多详细信息和与其他LINQ端口的比较

LINQ

In .NET, LINQ is frequently used for sorting, which provides a much nicer syntax over comparison functions, especially when objects need to be sorted by multiple fields. There're several ports of LINQ to PHP, including YaLinqo library*. With it, arrays can be sorted with a single line without writing complex comparison functions.

$sortedByName         = from($objects)->orderBy('$v->name');
$sortedByCount        = from($objects)->orderBy('$v->count');
$sortedByCountAndName = from($objects)->orderBy('$v->count')->thenBy('$v->name');

Comparisons can be further customized by passing a callback as a second argument, for example:

$sortedByFilenameNat  = from($objects)->orderBy('$v->filename', 'strnatcmp');

Here, '$v->count' is a shorthand for function ($v) { return $v->count; } (either can be used). These method chains return iterators, iterators can be transformed to arrays by adding ->toArray() in the end if needed.

Internally, orderBy and related methods call appropriate array sorting functions (uasort, krsort, multisort, usort etc.).

LINQ contains many more methods inspired by SQL: filtering, grouping, joining, aggregating etc. It's best suited for cases when complex transformations on arrays and objects need to be performed without relying on databases.

* developed by me, see readme for more details and comparison with other LINQ ports

九公里浅绿 2025-01-26 10:30:43

多维按键值的多维排序

自然形式的多维阵列按钥匙值进行,并且还保持原始顺序(不要随机键):

function multisortByKeyValue( $k, $arr ) {
    $ids   = array();
    $index = 1;

    foreach ( $arr as $key => $row ) {
        $ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
        $index ++;
    }

    natsort( $ids );

    $arr = array_merge( $ids, $arr );

    return $arr;
}

测试案例:

$arr = array(
    'id1' => array(
        'label'    => 'ID 1',
        'priority' => 30,
    ),
    'id2' => array(
        'label'    => 'ID 2',
        'priority' => 70,
    ),
    'id3' => array(
        'label'    => 'ID 3',
        'priority' => 20,
    ),
    'id4' => array(
        'label'    => 'ID 4',
        'priority' => 30,
    ),
);

$sorted = multisortByKeyValue( 'priority', $arr );

// $sorted equals to:
/*
array (
  'id3' => array (
    'label' => 'ID 3',
    'priority' => 20,
  ),
  'id1' => array (
    'label' => 'ID 1',
    'priority' => 30,
  ),
  'id4' => array (
    'label' => 'ID 4',
    'priority' => 30,
  ),
  'id2' => array (
    'label' => 'ID 2',
    'priority' => 70,
  ),
)
*/

Multidimensional sort by key value

Natural sort of a multidimensional array by a key value and also keep the original order(do not shuffle the main keys):

function multisortByKeyValue( $k, $arr ) {
    $ids   = array();
    $index = 1;

    foreach ( $arr as $key => $row ) {
        $ids[ $key ] = intval( $row[ $k ] ) . '-' . $index . '-' . $key;
        $index ++;
    }

    natsort( $ids );

    $arr = array_merge( $ids, $arr );

    return $arr;
}

Test case:

$arr = array(
    'id1' => array(
        'label'    => 'ID 1',
        'priority' => 30,
    ),
    'id2' => array(
        'label'    => 'ID 2',
        'priority' => 70,
    ),
    'id3' => array(
        'label'    => 'ID 3',
        'priority' => 20,
    ),
    'id4' => array(
        'label'    => 'ID 4',
        'priority' => 30,
    ),
);

$sorted = multisortByKeyValue( 'priority', $arr );

// $sorted equals to:
/*
array (
  'id3' => array (
    'label' => 'ID 3',
    'priority' => 20,
  ),
  'id1' => array (
    'label' => 'ID 1',
    'priority' => 30,
  ),
  'id4' => array (
    'label' => 'ID 4',
    'priority' => 30,
  ),
  'id2' => array (
    'label' => 'ID 2',
    'priority' => 70,
  ),
)
*/
も让我眼熟你 2025-01-26 10:30:43

这个页面非常全面,但我想添加更多关于太空船运算符(三向比较运算符)的强大实用程序——PHP7+ 的一个漂亮的孩子。

使用 spaceship 运算符实现多个排序条件

这在减少代码膨胀和提高可读性方面取得了巨大进步。

当编写自定义排序 (usort()/uasort()/uksort()) 函数来处理多个条件时,您只需要在运算符的两侧写入平衡数组并返回结果。 不再嵌套条件块或多次返回。

将从左到右遍历运算符两侧的元素,一次一个,并在遇到非平局或当所有元素都被比较后。

我的演示的示例数据:

$multidimArray = [
    'a' => [
        'boolean' => true,
        'natString' => 'text10',
        'object' => (object)['prop' => 2],
        'float' => -.5,
        'mixed' => []
    ],
    'b' => [
        'boolean' => true,
        'natString' => 'text12',
        'object' => (object)['prop' => 4],
        'float' => 0,
        'mixed' => null
    ],
    'c' => [
        'boolean' => false,
        'natString' => 'text100',
        'object' => (object)['prop' => 9],
        'float' => -.5,
        'mixed' => false
    ],
    'd' => [
        'boolean' => true,
        'natString' => 'text1',
        'object' => (object)['prop' => 9],
        'float' => -5,
        'mixed' => "\0"
    ],
    'e' => [
        'boolean' => false,
        'natString' => 'text2',
        'object' => (object)['prop' => 2],
        'float' => .5,
        'mixed' => ''
    ]
];

演示(为了避免 Stackoverflow 页面膨胀,请参阅演示链接以获取输出):

  • 排序逻辑:

    1. 布尔型 DESC(false = 0,true = 1,因此 true 在 false 之前)
    2. 浮动 ASC

      uasort($multidimArray, 函数($a, $b) {
          返回 [$b['boolean'], $a['float']] <=>; [$a['布尔值'], $b['浮动']];
      });
      
  • 排序逻辑:

    1. 混合 ASC
    2. 对象 ASC
    3. 布尔 ASC

      uasort($multidimArray, 函数($a, $b) {
          return [$a['mixed'], $a['object']->prop, $a['boolean']] <=>; [$b['mixed'], $b['object']->prop, $b['boolean']];
      });
      
  • 排序逻辑:

    1. 对象 ASC 的属性计数
    2. 混合 DESC 的可迭代性
    3. natString 长度 ASC
    4. natString ASC

      uasort($multidimArray, 函数($a, $b) {
          返回 [count(get_object_vars($a['object'])), is_iterable($a['mixed']), strlen($a['natString']), $a['natString']]
                 <=>
                 [count(get_object_vars($b['object'])), is_iterable($b['mixed']), strlen($b['natString']), $b['natString']];
      });
      

此语法允许您以优雅的方式对值、函数结果、深层嵌套数据和排序方向进行排序。对于处理非数据库数据的情况,这绝对值得放入您的 php 工具带中——因为当然 SQL 是一种更明智的技术。

您可以自行决定,从 PHP7.4 开始,您可以对这些匿名函数使用箭头语法。 具有箭头语法的相同脚本

This page is very comprehensive, but I want to add a bit more about the awesome utility of the spaceship operator (three way comparison operator) -- a beautiful child of PHP7+.

Using the spaceship operator to implement multiple sort conditions

This makes great strides in reducing code bloat and improving readability.

When writing your custom sort (usort()/uasort()/uksort()) function to process a multiple conditions, you only need to write balanced arrays on either side of the operator and return the outcome. No more nested condition blocks or multiple returns.

The elements from both sides of the operator will be traversed left to right, one at a time, and returning the evaluation as soon as a non-tie is encountered or when the elements have all been compared.

Sample data for my demonstrations:

$multidimArray = [
    'a' => [
        'boolean' => true,
        'natString' => 'text10',
        'object' => (object)['prop' => 2],
        'float' => -.5,
        'mixed' => []
    ],
    'b' => [
        'boolean' => true,
        'natString' => 'text12',
        'object' => (object)['prop' => 4],
        'float' => 0,
        'mixed' => null
    ],
    'c' => [
        'boolean' => false,
        'natString' => 'text100',
        'object' => (object)['prop' => 9],
        'float' => -.5,
        'mixed' => false
    ],
    'd' => [
        'boolean' => true,
        'natString' => 'text1',
        'object' => (object)['prop' => 9],
        'float' => -5,
        'mixed' => "\0"
    ],
    'e' => [
        'boolean' => false,
        'natString' => 'text2',
        'object' => (object)['prop' => 2],
        'float' => .5,
        'mixed' => ''
    ]
];

Demonstrations (to avoid Stackoverflow page bloat, please see the demo link for the outputs):

  • Sorting logic:

    1. boolean DESC (false = 0, true = 1, so trues before falses)
    2. float ASC

      uasort($multidimArray, function($a, $b) {
          return [$b['boolean'], $a['float']] <=> [$a['boolean'], $b['float']];
      });
      
  • Sorting logic:

    1. mixed ASC
    2. object ASC
    3. boolean ASC

      uasort($multidimArray, function($a, $b) {
          return [$a['mixed'], $a['object']->prop, $a['boolean']] <=> [$b['mixed'], $b['object']->prop, $b['boolean']];
      });
      
  • Sorting logic:

    1. property count of object ASC
    2. iterability of mixed DESC
    3. natString length ASC
    4. natString ASC

      uasort($multidimArray, function($a, $b) {
          return [count(get_object_vars($a['object'])), is_iterable($a['mixed']), strlen($a['natString']), $a['natString']]
                 <=>
                 [count(get_object_vars($b['object'])), is_iterable($b['mixed']), strlen($b['natString']), $b['natString']];
      });
      

This syntax allows you to sort values, functional outcomes, deep-nested data, and sorting direction in a elegant fashion. This is definitely worth putting in your php toolbelt ...for cases when you are processing non-database data -- because of course SQL would be a much more sensible technique.

At your own discretion, from PHP7.4 you can use arrow syntax with these anonymous functions. Same script with arrow syntax.

腻橙味 2025-01-26 10:30:43

排序功能来自 nspl

基本排序

// Sort array
$sorted = sorted([3, 1, 2]);

// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);

通过函数结果

// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');

// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; }); 

// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));

// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0

对多维阵列进行排序

// Sort multidimensional array (sort list of users by their names)
$users = [
    array('name' => 'Robert', 'age' => 20),
    array('name' => 'Alex', 'age' => 30),
    array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));

// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key

对象的排序阵列

// Lets assume we have class User(name, age) with properties name and age
// and public methods getName() and getAge()
$users = [
    new User('Robert', 20),
    new User('Alex', 30),
    new User('Jack', 25),
];

// Sort list of objects by property value (sort list of users by their name)
$sortedByName = sorted($users, propertyGetter('name'));
$sortedByNameDesc = sorted($users, true, propertyGetter('name'));

// propertyGetter('name') returns a function which takes an object
// and returns the value of its 'name' property

// Sort list of objects by method result (sort list of users by their age)
$sortedByAge = sorted($users, methodCaller('getAge'));
$sortedByAgeDesc = sorted($users, true, methodCaller('getAge'));

// methodCaller('getAge') returns a function which takes an object
// and returns the result of its getAge() method

使用比较函数进行排序

// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');

// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
    return chr($v1[0]) - chr($v2[0]);
});

您可以看到所有这些示例在这里

It is very convenient to sort arrays with sorted function from Nspl:

Basic sorting

// Sort array
$sorted = sorted([3, 1, 2]);

// Sort array in descending order
$sortedDesc = sorted([3, 1, 2], true);

Sorting by function result

// Sort array by the result of a given function (order words by length)
$sortedByLength = sorted(['bc', 'a', 'abc'], 'strlen');
$sortedByLengthDesc = sorted(['bc', 'a', 'abc'], true, 'strlen');

// Sort array by the result of user-defined function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], function($v) { return $v[0]; }); 

// Which is the same as
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], itemGetter(0));
$sortedByTheFirstCharacterDesc = sorted(['bc', 'a', 'abc'], true, itemGetter(0));

// itemGetter(0) returns a function which takes an argument with access by index/key
// and returns the value at index 0

Sorting multidimensional array

// Sort multidimensional array (sort list of users by their names)
$users = [
    array('name' => 'Robert', 'age' => 20),
    array('name' => 'Alex', 'age' => 30),
    array('name' => 'Jack', 'age' => 25),
];
$sortedByName = sorted($users, itemGetter('name'));
$sortedByNameDesc = sorted($users, true, itemGetter('name'));

// itemGetter('name') returns a function which takes an argument with access by index/key
// and returns the value of the 'name' key

Sorting array of objects

// Lets assume we have class User(name, age) with properties name and age
// and public methods getName() and getAge()
$users = [
    new User('Robert', 20),
    new User('Alex', 30),
    new User('Jack', 25),
];

// Sort list of objects by property value (sort list of users by their name)
$sortedByName = sorted($users, propertyGetter('name'));
$sortedByNameDesc = sorted($users, true, propertyGetter('name'));

// propertyGetter('name') returns a function which takes an object
// and returns the value of its 'name' property

// Sort list of objects by method result (sort list of users by their age)
$sortedByAge = sorted($users, methodCaller('getAge'));
$sortedByAgeDesc = sorted($users, true, methodCaller('getAge'));

// methodCaller('getAge') returns a function which takes an object
// and returns the result of its getAge() method

Sorting with a comparison function

// Sort with a comparison function (order words lexicographically with strcmp)
$sortedLexicographically = sorted(['bc', 'a', 'abc'], false, null, 'strcmp');

// Sort with user-defined comparison function (order words by the 1st character)
$sortedByTheFirstCharacter = sorted(['bc', 'a', 'abc'], false, null, function($v1, $v2) {
    return chr($v1[0]) - chr($v2[0]);
});

You can see all these examples here.

流云如水 2025-01-26 10:30:43

如果您想按钥匙值订购,则可以进行一条线条,优雅而清晰。这将按价格上涨订购。使用array_multisort和array_column。

   Array([0] => Array ( [name] => eggs [price] => 1 ) [1] => Array ( [name] => coffee [price] => 9.99 ) [2] => Array ( [name] => rice [price] => 4.04 ) )

   array_multisort (array_column($array, 'price'), SORT_ASC, $array);

生产

     Array ( [0] => Array ( [name] => eggs [price] => 1 ) [1] => Array ( [name] => rice [price] => 4.04 ) [2] => Array ( [name] => coffee [price] => 9.99 ) )

If you want to order by the key value, then you can do it one line, elegant and clear. This will order by the price ascending. Uses array_multisort and array_column.

   Array([0] => Array ( [name] => eggs [price] => 1 ) [1] => Array ( [name] => coffee [price] => 9.99 ) [2] => Array ( [name] => rice [price] => 4.04 ) )

   array_multisort (array_column($array, 'price'), SORT_ASC, $array);

to produce

     Array ( [0] => Array ( [name] => eggs [price] => 1 ) [1] => Array ( [name] => rice [price] => 4.04 ) [2] => Array ( [name] => coffee [price] => 9.99 ) )
清晰传感 2025-01-26 10:30:43

如果您想根据多个条件根据绝对最高值对数组进行排序,可以使用以下简单方法:

usort($arr, function($item, $nextItem) {
    return (max($nextItem->firstNumber, $nextItem->secondNumber)) - (max($item->firstNumber, $item->secondNumber));
});

示例:

$foo = new stdClass;
$foo->createdDate = '10';
$foo->uploadedDate = '5';

$bar = new stdClass;
$bar->createdDate = '1';
$bar->uploadedDate = '12';

$baz = new stdClass;
$baz->createdDate = '25';
$baz->uploadedDate = '0';


$arr = [$foo, $bar, $baz];

// Order array by the highest number between "createdDate" and "uploadedDate".
usort($arr, function($item, $nextItem) {
    return (max($nextItem->createdDate, $nextItem->uploadedDate)) - (max($item->createdDate, $item->uploadedDate));
});

结果:

array (
  0 => 
  (object) array(
     'createdDate' => '25',
     'uploadedDate' => '0',
  ),
  1 => 
  (object) array(
     'createdDate' => '1',
     'uploadedDate' => '12',
  ),
  2 => 
  (object) array(
     'createdDate' => '10',
     'uploadedDate' => '5',
  ),
)

If you want to sort an array based on the absolute highest value based on multiple criteria, here's an easy way to do it:

usort($arr, function($item, $nextItem) {
    return (max($nextItem->firstNumber, $nextItem->secondNumber)) - (max($item->firstNumber, $item->secondNumber));
});

Example:

$foo = new stdClass;
$foo->createdDate = '10';
$foo->uploadedDate = '5';

$bar = new stdClass;
$bar->createdDate = '1';
$bar->uploadedDate = '12';

$baz = new stdClass;
$baz->createdDate = '25';
$baz->uploadedDate = '0';


$arr = [$foo, $bar, $baz];

// Order array by the highest number between "createdDate" and "uploadedDate".
usort($arr, function($item, $nextItem) {
    return (max($nextItem->createdDate, $nextItem->uploadedDate)) - (max($item->createdDate, $item->uploadedDate));
});

Results in:

array (
  0 => 
  (object) array(
     'createdDate' => '25',
     'uploadedDate' => '0',
  ),
  1 => 
  (object) array(
     'createdDate' => '1',
     'uploadedDate' => '12',
  ),
  2 => 
  (object) array(
     'createdDate' => '10',
     'uploadedDate' => '5',
  ),
)
原野 2025-01-26 10:30:43

有几种分类数组的方法。我会提到一些完成该任务的方法。所有方法,我将提供一个被称为“ $数字”的整数数组。

$number = array(8,9,3,4,0,1,2);

这是创建数组的正常方法。假设我想按升序排序该数组。为此,可以使用“ sort()”方法。

<?php

    $number = array(8,9,3,4,0,1,2);
    sort($number);

   foreach ($number as $value) {
       echo $value."  ";
   }
?>

现在考虑一下输出,

”在此处输入图像说明“

您可以看到打印的号码数组已排序。如果您想将该数字数组分类为降序,则可以将“ rsort()”方法用于该任务。

<?php

     $number = array(8,9,3,4,0,1,2);
     rsort($number);

     foreach ($number as $value) {
        echo $value."  ";
     }
?>

考虑输出..

“在此处输入映像说明”

现在以降序排序。 。

$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);

<?php

   $number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
   asort($number);

   foreach ($number as $value) {
      echo $value."  ";
    }
?>

如果按其价值对降序进行排序,则可以使用“ Arsort()”方法。
假设您想根据数组的关键值对该数组进行排序。在此中,可以使用“ ksort()”方法。

<?php

     $number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
     ksort($number);

     foreach ($number as $value) {
         echo $value."  ";
     }
?>

现在考虑输出。

现在按其关键值对数组进行排序。如果您想根据其密钥值以降顺序对数组进行排序,则可以使用“ krsort()”方法。

<?php

    $number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
    krsort($number);

    foreach ($number as $value) {
       echo $value."  ";
    }
?>

现在,关联阵列按降序按关键值进行排序。查看输出。

这些是在PHP中以升序或降序排列数组的某些方法。我希望您能得到一个想法。谢谢!

There are several ways to sort an array.I will mention some methods for doing that task.fist of all , I will give an integer array which is called as '$numbers'.

$number = array(8,9,3,4,0,1,2);

This is the normal way to creating an array. Suppose that , I want to sort that array in ascending order.For that, 'sort()' method can be used.

<?php

    $number = array(8,9,3,4,0,1,2);
    sort($number);

   foreach ($number as $value) {
       echo $value."  ";
   }
?>

Now consider the output of that,

enter image description here

You can see printed number array is sorted. If you want to that number array to be sort is descending order, 'rsort()' method can be use for that task.

<?php

     $number = array(8,9,3,4,0,1,2);
     rsort($number);

     foreach ($number as $value) {
        echo $value."  ";
     }
?>

consider the output..

enter image description here

Now array is sorted in descending order.Ok, Let's consider an associative array.I will give an associative array(Associative array means that, An array whose each index has unique key value.) like this,

$number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);

So ,Now I want to sort this array in ascending order according their value.'asort()' method can be used for that.

<?php

   $number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
   asort($number);

   foreach ($number as $value) {
      echo $value."  ";
    }
?>

If sorting descending order according their value,'arsort()' method can be used.
Suppose that you want to sort that array according their key value. In this , 'ksort()' method can be use.

<?php

     $number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
     ksort($number);

     foreach ($number as $value) {
         echo $value."  ";
     }
?>

Now consider the output.
enter image description here

Now array is sorted according their key value.If You want to sort the array in descending order according their key value,'krsort()' method can be used.

<?php

    $number = array('eight'=>8,'nine'=>9,'three'=>3,'fore'=>4,'zero'=>0,'one'=>1,'two'=>2);
    krsort($number);

    foreach ($number as $value) {
       echo $value."  ";
    }
?>

Now associative array is sorted in descending order according their key value.Look at the output.
enter image description here

These are the some methods for sorting an array in ascending or descending order in php.I hope to you could get an idea.Thank you!

闻呓 2025-01-26 10:30:43

如果某人想要一个更简单的解决方案来操纵数组,只需使用Laravel Collection软件包,该软件包具有实现的分类函数,可以简单地通过钥匙进行排序即可。

$collection->sortBy('forename')->sortBy('surname');

即,为了首先按A,B,然后C进行排序,正确的子句将为

sortBy('c')->sortBy('b')->sortBy('a')

https:/ /packagist.org/packages/tightenco/collect

If someone wants a simpler solution to manipulate arrays, just use Laravel Collection package which has an implemented sortBy function that lets your sort by keys simply.

$collection->sortBy('forename')->sortBy('surname');

i.e., in order to sort first by a, then b, then c, the correct clause would be

sortBy('c')->sortBy('b')->sortBy('a')

https://packagist.org/packages/tightenco/collect

你的往事 2025-01-26 10:30:43

这个答案是关于多列排序的,其中应在每个一维元素中对数组进行排序。
这与多维形式不同,因为每个元素仅由各种键=&gt;值对组成。

function fncCmp( array $ItmOne, array $ItmTwo ) {       ; # callback for sorting items (which are arrays) by values at specific indexes
  $strCmpOne = $ItmOne[ 'ColOne' ] . $ItmOne[ 'ColThr' ]; # build compound values
  $strCmpTwo = $ItmTwo[ 'ColOne' ] . $ItmTwo[ 'ColThr' ]; #   to compare
  return $strCmpOne <=> $strCmpTwo                      ; # pass back comparison-result
} # fncCmp

$arrDat = array(                                                       # define an array of items
  array( 'ColOne' => 'Val2', 'ColTwo' => 'Val8', 'ColThr' => 'Val6' )  #   each of which
 ,array( 'ColOne' => 'Val2', 'ColTwo' => 'Val9', 'ColThr' => 'Val4' )  #   is an
 ,array( 'ColOne' => 'Val1', 'ColTwo' => 'Val7', 'ColThr' => 'Val5' )  #   array of
)                                                                    ; #   fields
var_dump       ( $arrDat           )                                 ; # emit items before sort
$bolSrt = usort( $arrDat, 'fncCmp' )                                 ; # sort the array by comparing elements
var_dump       ( $arrDat           )                                 ; # emit items after  sort

This answer is about multi-column sort, where the array should be sorted by, within each one-dimensional element, the values of non-contiguous indexes.
This is different from multi-dimensional sort, because each element is composed of only various Key=>Value pairs.

function fncCmp( array $ItmOne, array $ItmTwo ) {       ; # callback for sorting items (which are arrays) by values at specific indexes
  $strCmpOne = $ItmOne[ 'ColOne' ] . $ItmOne[ 'ColThr' ]; # build compound values
  $strCmpTwo = $ItmTwo[ 'ColOne' ] . $ItmTwo[ 'ColThr' ]; #   to compare
  return $strCmpOne <=> $strCmpTwo                      ; # pass back comparison-result
} # fncCmp

$arrDat = array(                                                       # define an array of items
  array( 'ColOne' => 'Val2', 'ColTwo' => 'Val8', 'ColThr' => 'Val6' )  #   each of which
 ,array( 'ColOne' => 'Val2', 'ColTwo' => 'Val9', 'ColThr' => 'Val4' )  #   is an
 ,array( 'ColOne' => 'Val1', 'ColTwo' => 'Val7', 'ColThr' => 'Val5' )  #   array of
)                                                                    ; #   fields
var_dump       ( $arrDat           )                                 ; # emit items before sort
$bolSrt = usort( $arrDat, 'fncCmp' )                                 ; # sort the array by comparing elements
var_dump       ( $arrDat           )                                 ; # emit items after  sort
等待我真够勒 2025-01-26 10:30:43

最简单的方法是使用 usort 函数对数组进行排序,无需任何循环:
下面是一个示例:

   $array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);

这将按降序排序:

usort($array_compare, function($a, $b) {
        return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
    });

这将按升序排序:

usort($array_compare, function($a, $b) {
        return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
    });

The simplest is to use usort function to sort array without any looping :
Below is an example :

   $array_compare= array("0" =>4,"1"=>2,"2"=>500,"3"=>100);

This will sort in desending order :

usort($array_compare, function($a, $b) {
        return ($b['x1'] - $a['x1']) > 0 ? 1 :-1;
    });

This will sort in asending order :

usort($array_compare, function($a, $b) {
        return ($b['x1'] - $a['x1']) < 0 ? 1 :-1;
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文