我怎么能进行排序在PHP中的数组和数据? [英] How can I sort arrays and data in PHP?

查看:104
本文介绍了我怎么能进行排序在PHP中的数组和数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

由于巨大的和不断重复量的我如何整理我的唯一一个数组的雪花?的问题,这是在PHP基本排序方法的参考集合。请关闭不显着不同的是这一次的副本的任何问题。


我怎么排序PHP中的数组?结果
我如何排序的复杂的数组中的PHP?结果
我如何在PHP中排序对象的数组?



  1. 基本一维数组;含。多维数组,包括。对象数组;含。排序基于另一个一个阵列

  2. 排序与SPL

  3. 稳定的排序

有关使用PHP的现有职能看1,对排序算法学术在详细回答的实际答案(其中PHP的功能实现,哪些是你的可能的需要真的,真的很复杂的情况下),见2。


解决方案

基本一维数组

  $阵列=阵列(3,5,2,8);

适用排序功能:


  • 排序

  • rsort

  • ASORT

  • arsort

  • natsort

  • natcasesort

  • ksort

  • krsort

那些之间的区别是关键值关联仅仅是否被保持(在 A 函数),无论排序低到高或反向(研究),无论排序值或键( K ),它是如何比较值( NAT 与正常)。请参见 http://php.net/manual/en/array.sorting.php 一个概述,并链接进一步的细节。

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

  $阵列=阵列(
    阵列('富'=>'酒吧','巴兹'=> 42),
    阵列('富'=> ...巴兹'=> ...)
    ...
);

如果要排序 $阵列每个条目的key'富',你需要的自定义比较函数的。以上排序和相关职能上,他们知道如何比较和排序简单值工作。 PHP不只是知道做什么用的复值的如阵列('富'=>'酒吧','巴兹'=> 42)虽然;所以你需要告诉它。

要做到这一点,你需要创建一个比较函数的。这个函数有两个元素,必须返回 0 如果这些元素被认为是平等的,如果第一个不是 0 低的值值越低,比 0 如果第一个值越高高的值。这是所有的需要:

 函数CMP(数组$ A,数组$ B){
    如果($ A ['富'] LT; $ B ['富']){
        返回-1;
    }否则如果($ A ['富']> $ B ['富']){
        返回1;
    }其他{
        返回0;
    }
}

通常情况下,你会希望使用匿名函数作为回调。如果你想使用方法或静态方法,请参阅PHP 其他方式>。

您再使用这些函数之一:

此外,他们只在是否保留键 - 值关联和排序值或键有所不同。阅读他们的文档以了解详情。

实例:

  usort($数组,'CMP');

usort 将采取从阵列中两个项目,并与他们打电话给你的 CMP 功能。因此, CMP() $ A 被称为阵列('富'=&GT ;'酒吧','巴兹'=> 42) $ b 另一个阵列('富'= > ...巴兹'=> ...)。该函数然后返回到 usort 该值是大于或他们是否都是平等的。 usort 重复这个过程,传递不同的值 $ A $ B 直到数组进行排序。在 CMP 函数将被调用很多次,至少的一样有在 $数组值多次,其值的不同组合对 $ A $ b 每次

要习惯这个想法,试试这个:

 函数CMP($ A,$ B){
    所谓的CMP用$一个:回声,PHP_EOL;
    后续代码var_dump($ A);
    回声'和$ b:'PHP_EOL;
    后续代码var_dump($ B);
}

,你却定义自定义的方式来比较两个项目,这就是你所需要的。这适用于各种价值观。

顺便说一下,这适用于任何值,这些值不必是复杂的阵列。如果你有你想要做一个自定义比较,你可以做到这数字过于简单阵列上。

自定义数值比较

如果你想通过巴兹键,也就是数字进行排序,所有你需要做的是:

 函数CMP(数组$ A,数组$ B){
    返回$ a ['巴兹'] - $ B ['巴兹'];
}

由于数学电源这将返回一个值< 0,0或> 0取决于是否 $ A 低于,等于或大于 $大一些的B

请注意,这不会对浮球正常工作价值,因为它们会被降低到 INT 而失去precision。使用明确的 1 0 1 的返回值,而不是

对象

如果你有对象的数组,它的工作原理是相同的:

 函数CMP($ A,$ B){
    返回$ A->巴兹 - $ B->巴兹;
}

功能

您可以做任何你需要一个比较函数里面包括调用函数:

 函数CMP(数组$ A,数组$ B){
    返回someFunction($ A ['巴兹']) - someFunction($ B ['巴兹']);
}

字符串

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

 函数CMP(数组$ A,数组$ B){
    返回STRCMP($ A ['富'],$ B ['富']);
}

STRCMP 究竟是干什么的预期的 CMP 在这里,它返回 1 0 1

飞船运营商

PHP 7引入了飞船运营商,该统一,简化等于/小/不是跨类型的比较大的:

 函数CMP(数组$ A,数组$ B){
    返回$ a ['富']< = GT; $ B ['富'];
}

由多个字段排序

如果你想通过主要排序,但如果是相等的两个元素排序巴兹

 函数CMP(数组$ A,数组$ B){
    如果(($ CMP = STRCMP($ A ['富'],$ B ['富']))!== 0){
        返回$ CMP;
    }其他{
        返回$ a ['巴兹'] - $ B ['巴兹'];
    }
}

对于那些熟悉,这相当于与 SQL查询ORDER BY美孚,巴兹。结果
另请参见这个非常整齐速记版本和的如何动态地创建这样的比较功能键任意数量。

分拣成手动,静态秩序

如果你想元素进行排序成手动秩序之类的富,酒吧,巴兹的:

 函数CMP(数组$ A,数组$ B){
    静态$为了=阵列('富','酒吧','巴兹');
    返回array_search($ A ['富'],$顺序) - array_search($ B ['富'],$顺序);
}


有关上述所有,如果你使用PHP 5.3或更高版本(你真的应该),使用匿名函数缩短code和以避免另一场全球性功能左右浮动:

  usort($阵列功能(数组$ A,数组$ B){$返回一个['巴兹']  -  $ B ['巴兹'];});

这是多么简单的排序复杂的多维数组即可。再次,只是觉得在的教学PHP如何分辨其中的两个项目是大的条款;让PHP做实际的排序。

也是所有上述情况,以升序和降序之间切换,简单地交换 $ A $ B 周围的论点。例如:

 返回$一个['巴兹']  -  $ B ['巴兹']; // 上升
返回$ B ['巴兹'] - $ A ['巴兹']; //下降

排序基于另一个

一个阵列

然后还有奇特的 在array_multisort ,它可以让您排序一个阵列基于另一个:

  $ ARRAY1 =阵列(4,6,1);
$数组2 =阵列('A','B','C');

下面预期的结果将是:

  $数组2 =阵列('C','A','B'); // $的的ARRAY1有序

使用在array_multisort 到达:

 在array_multisort($数组1,$数组2);



  

<子>如果你有更多的共同的情况下,随意修改这个答案。


Due to the enormous and ever repeating amount of "How do I sort my unique snowflake of an array?" questions, this is a reference collection of basic sorting methods in PHP. Please close any question which does not markedly differ as a duplicate of this one.

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. Multi dimensional 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.

解决方案

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.

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);


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

这篇关于我怎么能进行排序在PHP中的数组和数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆