php 多维数组自定义排序_高级PHP:自定义排序和多维排序

php 多维数组自定义排序

Everyone has probably been asked, "Which (food / movie / dress / whatever) do you like better, A or B?" Really, there's only three ways to answer this type of question: "I like A better" or "I like B better" or "I like them the same."

可能每个人都被问到:“您喜欢哪个(食物/电影/衣服/其他),A或B? 确实,只有三种方法可以回答此类问题:“我更喜欢A”或“我更喜欢B”或“我同样喜欢它们”。

This is ALL you need to know in order to understand how to use the usort() function in PHP. The usort() function lets you sort an array using a function that you've created to compare two things. All PHP asks the function to do is tell it which it likes better: $a or $b.

这就是您需要了解的所有内容,以便了解如何在PHP中使用usort()函数。 使用usort()函数,您可以使用为比较两件事而创建的函数对数组进行排序。 所有PHP要求函数执行的操作都是告诉它哪个更好:$ a或$ b。

You don't have to worry about the array itself - all you do is create a function that takes in two parameters $a and $b. Then your function does whatever it needs to do in order to determine whether $a is greater than $b. If $a is greater than $b, the function should return a 1. If $b is greater, then the function should return a -1. If $a and $b are the same, then the function returns a 0.

您不必担心数组本身-您要做的就是创建一个接受两个参数$ a和$ b的函数。 然后,您的函数将执行需要执行的所有操作,以确定$ a是否大于$ b。 如果$ a大于$ b,则函数应返回1。如果$ b大于,则函数应返回-1。 如果$ a和$ b相同,则该函数返回0。

Someone wanted to be able to sort an array of strings by the first character after the dash in the string. In other words, their array looked like:

有人希望能够按字符串中破折号后的第一个字符对字符串数组进行排序。 换句话说,它们的数组如下所示:

$myArray = array(
  "foo1-Anthony",
  "foo2-Xavier",
  "foo3-Henry",
  "foo4-Jarrod"
);

...and they wanted to sort by the name. Obviously, none of the built-in sorting functions will do, so usort lets us do our own thing. In this case, I wrote a function to split the strings given by the dash, so I could do a simple comparison on the strings the person wanted to test:

...他们想按名称排序。 显然,内置的排序功能都不起作用,因此usort可以让我们做自己的事情。 在这种情况下,我编写了一个函数来分割破折号给出的字符串,因此我可以对该人想要测试的字符串进行简单的比较:

function sortAfterTheDash($a,$b)
{
  list($whateverA,$testA) = explode("-",$a);
  list($whateverB,$testB) = explode("-",$b);
  
  if($testA > $testB) { return 1; }
  if($testA < $testB) { return -1; }
  if($testA == $testB) { return 0; }
}

To call it, we simply run:

要调用它,我们只需运行:

usort($myArray, "sortAfterTheDash");

The result is that $myArray gets sorted the way we want it, using the strings after the dash! Basically what usort() does is go through your array, two elements at a time, then passes those two elements to your function. If you were to do the same thing manually, you would do it like this:

结果是$ myArray使用破折号后的字符串按我们想要的方式排序! 基本上,usort()的作用是一次遍历数组,一次两个元素,然后将这两个元素传递给函数。 如果您要手动执行相同的操作,则应执行以下操作:

$newArray = array();
$result = sortAfterTheDash("foo1-Anthony","foo2-Xavier");
// Based on the result, insert Anthony into the array first, and Xavier second.
// $newArray = array("foo1-Anthony","foo2-Xavier");

$result = sortAfterTheDash("foo2-Xavier","foo3-Henry");
// Based on the result, insert Henry into the array BEFORE Xavier
// $newArray = array("foo1-Anthony","foo3-Henry","foo2-Xavier");

$result1 = sortAfterTheDash("foo3-Henry","foo4-Jarrod");
$result2 = sortAfterTheDash("foo4-Jarro","foo2-Xavier");
// Based on the results, insert Jarrod into the array BETWEEN Henry and Xavier
// $newArray = array("foo1-Anthony","foo3-Henry","foo4-Jarrod","foo2-Xavier");

Now let's move onto a more advanced topic - sorting a multi-dimensional array using array_multisort(). A LOT of people have no idea how to use this very powerful function, but it's usually because it's one of the few functions that requires a fair amount of "preparation" to use. Fear not - I have a shortcut that I will share with you, but let's understand array_multisort() first. Let's say you have an array that looks like this:

现在,让我们进入一个更高级的主题-使用array_multisort()对多维数组进行排序。 很多人不知道如何使用此功能非常强大的功能,但这通常是因为它是少数需要大量“准备工作”才能使用的功能之一。 别担心-我有一个捷径可以与您分享,但让我们首先了解array_multisort()。 假设您有一个看起来像这样的数组:

$people = array(
  "Joe" => array("Last Name" => "Schmoe", "Income" => 20000),
  "Bill" => array("Last Name" => "Gaites", "Income" => 200000000),
  "William" => array("Last Name" => "Gaites", "Income" => 200),
  "Mary" => array("Last Name" => "Bartley", "Income" => 100000),
);

Now let's say you want to sort by ascending "Income". Unfortunately, array_multisort doesn't just take a field name and sort on it. What you have to do is first extract the values you want to sort by to ANOTHER array. So in this case, you would want to loop through $people and create a NEW array called $incomes:

现在,假设您要按升序排列“收入”。 不幸的是,array_multisort不仅接受字段名称并对其进行排序。 您要做的是首先将要排序的值提取到另一个数组中。 因此,在这种情况下,您需要遍历$ people并创建一个名为$ incomes的新数组:

$incomes = array();
foreach($people as $person)
{
  $incomes[] = $person["Income"];
}

Then you would call array_multisort like this:

然后,您将这样调用array_multisort:

array_multisort($incomes,SORT_ASC,$people);

What happens is that array_multisort FIRST sorts the $incomes array in ascending order (SORT_ASC) and keeps track of which record moved to which spot (e.g. record 4, which was 100000, is now record 3 after being sorted). It creates a map like this:

发生的情况是array_multisort FIRST以升序(SORT_ASC)对$ incomes数组进行排序,并跟踪哪个记录移动到哪个位置(例如,记录4为100000,现在在排序后成为记录3)。 它创建一个像这样的地图:

Index 0 is now at Index 1

索引0现在位于索引1

Index 1 is now at Index 3

索引1现在位于索引3

Index 2 is now at Index 0

索引2现在位于索引0

Index 3 is now at Index 2

索引3现在位于索引2

Once it has this map of old and new orders, it goes to the $people array and applies the same re-arrangements, so that whatever was in the first spot ("Joe") is now in the second spot, whatever was originally in the second spot ("Bill") is now in the third spot, and so on and so on until $people has been rearranged into the new order.

一旦有了这张旧订单和新订单的地图,它就会转到$ people数组并应用相同的重新安排,因此,第一位的内容(“ Joe”)现在位于第二位的内容,无论原先的位置是什么第二个位置(“ Bill”)现在位于第三个位置,依此类推,直到将$ people重新排列为新顺序。

Now let's say you wanted to order by more than one column. For example, let's say you wanted to start by sorting the "Last Name" column as we've already done with "Income":

现在,假设您要订购多个列。 例如,假设您要像对“收入”所做的那样首先对“姓氏”列进行排序:

$lnames = array();
foreach($people as $person)
{
  $lnames[] = $person["Last Name"];
}
array_multisort($lnames,SORT_ASC,$people);

Since we have two people with the same last name ("Gaites"), let's say we also want to specify the "Income" as a second sorting parameter in descending order, so that the Gaites are listed from richest to poorest! No problem - it's just another array and a couple parameters in our array_multisort call. The final code would look like:

因为我们有两个姓氏相同的人(“盖特”),所以我们也想将“收入”指定为降序的第二个排序参数,以便将盖特从最富到最穷列出! 没问题-这只是另一个数组和我们array_multisort调用中的几个参数。 最终代码如下所示:

$lnames = array();
$incomes = array();
foreach($people as $person)
{
  $lnames[] = $person["Last Name"];
  $incomes[] = $person["Income"];
}
array_multisort($lnames,SORT_ASC,$incomes,SORT_DESC,$people);

This would sort the $people array to be in the order of Mary Bartley, Bill Gaites, William Gaites, and finally Joe Schmoe.

这将使$ people数组排序为Mary Bartley,Bill Gaites,William Gaites,最后是Joe Schmoe。

Okay, to finish, I promised you a shortcut. A while back I came across a snippet of code written by someone named "Ichier" as part of a CMS system or something. This brilliant little function, array_csort, basically handles all the dirty work for you in array_multisort and turns multi-dimensional array sorting into a single line of code:

好吧,最后,我答应了您一个捷径。 不久前,我遇到了一个名为“ Ichier”的人编写的一段代码,作为CMS系统之类的内容。 这个出色的小函数array_csort基本上可以为您处理array_multisort中的所有脏活,并将多维数组排序变成一行代码:

// Example of using it with our $people array:
$people = array_csort($people,"Last Name",SORT_ASC,"Income",SORT_DESC);

// And here's the function definition:

//coded by Ichier2003
function array_csort()
{
	$args = func_get_args();
	$marray = array_shift($args); 
	$msortline = 'return(array_multisort(';
	$i = 0;
	foreach ($args as $arg) {
		$i++;
		if (is_string($arg)) {
			foreach ($marray as $row) {
				$sortarr[$i][] = $row[$arg];
			}
		} else {
			$sortarr[$i] = $arg;
		}
		$msortline .= '$sortarr['.$i.'],';
	}
	$msortline .= '$marray));';
	eval($msortline);
	return $marray;
}

Here is the home of the function:

这是函数的所在地:

http://www.ichier.de/coding/functions/array_csort.html http://www.ichier.de/coding/functions/array_csort.html

Enjoy!

请享用!

翻译自: https://www.experts-exchange.com/articles/4213/Advanced-PHP-Custom-Sorting-and-Multidimensional-Sorting.html

php 多维数组自定义排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值