php 如何按PHP中给定键的值对关联数组的数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1597736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort an array of associative arrays by value of a given key in PHP?
提问by Matt
Given this array:
鉴于此数组:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
I would like to sort $inventory's elements by price to get:
我想$inventory按价格对 的元素进行排序以获得:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
How can I do this?
我怎样才能做到这一点?
回答by Josh Davis
You are right, the function you're looking for is array_multisort().
你是对的,你正在寻找的功能是array_multisort().
Here's an example taken straight from the manual and adapted to your case:
这是直接取自手册并适合您的情况的示例:
$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);
As of PHP 5.5.0 you can use array_column() instead of that foreach
从 PHP 5.5.0 开始,您可以使用 array_column() 而不是 foreach
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
回答by Mark Amery
PHP 7+
PHP 7+
As of PHP 7, this can be done concisely using usortwith an anonymous functionthat uses the spaceship operatorto compare elements.
从 PHP 7 开始,这可以通过使用spaceship 运算符来比较元素usort的匿名函数来简洁地完成。
You can do an ascending sort like this:
您可以像这样进行升序排序:
usort($inventory, function ($item1, $item2) {
return $item1['price'] <=> $item2['price'];
});
Or a descending sort like this:
或者像这样的降序排序:
usort($inventory, function ($item1, $item2) {
return $item2['price'] <=> $item1['price'];
});
To understand how this works, note that usorttakes a user-provided comparison function that must behave as follows (from the docs):
要了解这是如何工作的,请注意usort采用用户提供的比较函数,该函数的行为必须如下(来自文档):
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
如果第一个参数被认为分别小于、等于或大于第二个参数,则比较函数必须返回一个小于、等于或大于零的整数。
And note also that <=>, the spaceship operator,
还要注意的是<=>,飞船操作员,
returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater
如果两个操作数相等,则返回 0,如果左侧更大则返回 1,如果右侧更大则返回 -1
which is exactly what usortneeds. In fact, almost the entire justification given for adding <=>to the language in https://wiki.php.net/rfc/combined-comparison-operatoris that it
这正是usort需要的。事实上,<=>在https://wiki.php.net/rfc/combined-comparison-operator 中添加语言的几乎全部理由是
makes writing ordering callbacks for use with
usort()easier
使编写排序回调
usort()更容易使用
PHP 5.3+
PHP 5.3+
PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usortto sort our array, but it's a little more verbose and harder to understand:
PHP 5.3 引入了匿名函数,但还没有 spaceship 运算符。我们仍然可以使用usort对数组进行排序,但它有点冗长且难以理解:
usort($inventory, function ($item1, $item2) {
if ($item1['price'] == $item2['price']) return 0;
return $item1['price'] < $item2['price'] ? -1 : 1;
});
Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price'], we can'tsafely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usorthas to return integers for usortto work properly:
请注意,尽管处理整数值的比较器只返回值的差值是很常见的,例如$item2['price'] - $item1['price'],但在这种情况下我们不能安全地这样做。这是因为在提问者的示例中价格是浮点数,但我们传递给的比较函数usort必须返回整数usort才能正常工作:
Returning non-integervalues from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
从比较函数返回非整数值,例如 float,将导致内部转换为回调返回值的整数。因此,诸如 0.99 和 0.1 之类的值都将转换为整数值 0,这会将这些值比较为相等。
This is an important trap to bear in mind when using usortin PHP 5.x! My original version of this answermade this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is preciselythe reason that the easier-to-use spaceship operator was added to the language in PHP 7.
这是usort在 PHP 5.x 中使用时要记住的一个重要陷阱!我对这个答案的原始版本犯了这个错误,但我显然在没有人注意到严重错误的情况下在数千次观看中获得了十次赞成。像我这样的笨蛋很容易搞砸比较器函数,这正是PHP 7 语言中添加了更易于使用的宇宙飞船运算符的原因。
回答by Mariano Iglesias
While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:
虽然其他人正确地建议使用array_multisort(),但出于某种原因似乎没有答案承认 的存在array_column(),这可以大大简化解决方案。所以我的建议是:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
回答by zombat
Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:
由于您的数组元素本身就是带有字符串键的数组,因此最好的办法是定义一个自定义比较函数。这非常快速和容易做到。尝试这个:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
Produces the following:
产生以下内容:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
回答by Danielzt
I ended on this:
我就此结束:
function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}
array_multisort($sortarray, SORT_ASC, $array);
}
Just call the function, passing the array and the name of the field of the second level array. Like:
只需调用该函数,传递数组和二级数组的字段名称即可。喜欢:
sort_array_of_array($inventory, 'price');
回答by kenorb
回答by danamlund
$inventory =
array(array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
function pricesort($a, $b) {
$a = $a['price'];
$b = $b['price'];
if ($a == $b)
return 0;
return ($a > $b) ? -1 : 1;
}
usort($inventory, "pricesort");
// uksort($inventory, "pricesort");
print("first: ".$inventory[0]['type']."\n\n");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)
// foreach prints the same for usort and uksort.
foreach($inventory as $i){
print($i['type'].": ".$i['price']."\n");
}
outputs:
输出:
first: pork
pork: 5.43
fruit: 3.5
milk: 2.9
回答by Kamal
From Sort an array of associative arrays by value of given key in php:
uasort (http://php.net/uasort) allows you to sort an array by your own defined function. In your case, that's simple:
uasort ( http://php.net/uasort) 允许您通过自己定义的函数对数组进行排序。在你的情况下,这很简单:
$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);
function cmp($a, $b) {
return $a['price'] > $b['price'];
}
uasort($array, "cmp");
回答by Nefelim
Was tested on 100 000 records:Time in seconds(calculated by funciton microtime). Only for unique values on sorting key positions.
在 100 000 条记录上进行了测试:以秒为单位的时间(由函数 microtime 计算)。 仅用于排序关键位置的唯一值。
Solution of function of @Josh Davis:Spended time: 1.5768740177155
@Josh Davis 的函数解决方案:花费时间:1.5768740177155
Mine solution:Spended time: 0.094044923782349
我的解决方案:花费时间:0.094044923782349
Solution:
解决方案:
function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
if (empty($data) or empty($sortKey)) return $data;
$ordered = array();
foreach ($data as $key => $value)
$ordered[$value[$sortKey]] = $value;
ksort($ordered, $sort_flags);
return array_values($ordered); *// array_values() added for identical result with multisort*
}
回答by mirado
I use uasortlike this
我uasort这样用
<?php
$users = [
[
'username' => 'joe',
'age' => 11
],
[
'username' => 'rakoto',
'age' => 21
],
[
'username' => 'rabe',
'age' => 17
],
[
'username' => 'fy',
'age' => 19
],
];
uasort($users, function ($item, $compare) {
return $item['username'] >= $compare['username'];
});
var_dump($users);

