php 如何按值对多维数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2699086/
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 Multi-dimensional Array by Value?
提问by stef
How can I sort this array by the value of the "order" key? Even though the values are currently sequential, they will not always be.
如何按“order”键的值对这个数组进行排序?尽管这些值当前是连续的,但它们并不总是如此。
Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)
回答by Christian Studer
Try a usort, If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:
试试usort,如果你还在 PHP 5.2 或更早版本,你必须先定义一个排序函数:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
Starting in PHP 5.3, you can use an anonymous function:
从 PHP 5.3 开始,您可以使用匿名函数:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
And finally with PHP 7 you can use the spaceship operator:
最后,在 PHP 7 中,您可以使用spaceship 运算符:
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.
要将其扩展到多维排序,请在第一个排序元素为零时引用第二个/第三个排序元素 - 最好在下面解释。您还可以使用它对子元素进行排序。
usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
If you need to retain key associations, use uasort()- see comparison of array sorting functionsin the manual
如果需要保留键的关联,使用uasort()- 参见手册中数组排序函数的比较
回答by o0'.
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
aasort($your_array,"order");
回答by Tom Haigh
I use this function :
我使用这个功能:
function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
$sort_col = array();
foreach ($arr as $key=> $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
array_sort_by_column($array, 'order');
回答by Jan Fabry
I usually use usort, and pass my own comparison function. In this case, it is very simple:
我通常使用usort,并传递我自己的比较函数。在这种情况下,它非常简单:
function compareOrder($a, $b)
{
return $a['order'] - $b['order'];
}
usort($array, 'compareOrder');
In PHP 7 using spaceship operator:
在 PHP 7 中使用飞船操作符:
usort($array, function($a, $b) {
return $a['order'] <=> $b['order'];
});
回答by ajuchacko91
One approach to achieve this would be like this
实现这一目标的一种方法是这样的
$new = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3,
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2,
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1,
],
];
$keys = array_column($new, 'order');
array_multisort($keys, SORT_ASC, $new);
var_dump($new);
Result:
结果:
Array
(
[0] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
)
回答by B.K
To sort the array by the value of the "title" key use:
要按“title”键的值对数组进行排序,请使用:
uasort($myArray, function($a, $b) {
return strcmp($a['title'], $b['title']);
});
strcmpcompare the strings.
strcmp比较字符串。
uasort()maintains the array keys as they were defined.
uasort()维护定义的数组键。
回答by Nitrodbz
$sort = array();
$array_lowercase = array_map('strtolower', $array_to_be_sorted);
array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $alphabetically_ordered_array);
This takes care of both upper and lower case alphabets.
这会处理大写和小写字母。
回答by Ghanshyam Nakiya
回答by Minwork
The most flexible approach would be using this method
最灵活的方法是使用这种方法
Arr::sortByKeys(array $array, $keys, bool $assoc = true): array
here's why:
原因如下:
You can sort by any key (also nested like
'key1.key2.key3'or['k1', 'k2', 'k3'])Works both on associative and not associative arrays (
$assocflag)It doesn't use reference - return new sorted array
您可以按任何键排序(也可以嵌套,例如
'key1.key2.key3'或['k1', 'k2', 'k3'])适用于关联和非关联数组(
$assoc标志)它不使用引用 - 返回新的排序数组
In your case it would be as simple as:
在你的情况下,它会很简单:
$sortedArray = Arr::sortByKeys($array, 'order');
This method is a part of this library.
这个方法是这个库的一部分。
回答by tony gil
Let's face it: php does NOT have a simple out of the box function to properly handle every array sort scenario.
让我们面对现实:php 没有一个简单的开箱即用的功能来正确处理每个数组排序场景。
This routine is intuitive, which means faster debugging and maintenance:
这个例程很直观,这意味着更快的调试和维护:
// automatic population of array
$tempArray = array();
$annotations = array();
// ... some code
// SQL $sql retrieves result array $result
// $row[0] is the ID, but is populated out of order (comes from
// multiple selects populating various dimensions for the same DATE
// for example
while($row = mysql_fetch_array($result)) {
$needle = $row[0];
arrayIndexes($needle); // create a parallel array with IDs only
$annotations[$needle]['someDimension'] = $row[1]; // whatever
}
asort($tempArray);
foreach ($tempArray as $arrayKey) {
$dataInOrder = $annotations[$arrayKey]['someDimension'];
// .... more code
}
function arrayIndexes ($needle) {
global $tempArray;
if (!in_array($needle,$tempArray)) {
array_push($tempArray,$needle);
}
}

