[英]Sort array by two fields values with grouping
UPDATE: I get array order by ID, and with groups together, as you can see, every calss come together. 更新:我通过ID获得数组顺序,并且将组组合在一起,如您所见,每一次校准都在一起。 I want to sort it first by ID, from biggest to smallest (to reverse to array), and then in every Class to sort by the Name I will show example to make it clear. 我想首先按ID对其进行排序,从最大到最小(反向到数组),然后在每个Class中按名称排序,我将显示示例以使其清楚。
I have this array: 我有这个数组:
Array
(
[0] => Array
(
[0] => 1 //ID
[1] => 88 //Class
[2] => 'a' //Name
)
[1] => Array
(
[0] => 2 //ID
[1] => 88 //Class
[2] => 'b' //Name
)
[2] => Array
(
[0] => 3 //ID
[1] => 7 //Class
[2] => 'v' //Name
)
[3] => Array
(
[0] => 4 //ID
[1] => 332 //Class
[2] => 'd' //Name
)
[4] => Array
(
[0] => 5 //ID
[1] => 332 //Class
[2] => 'z' //Name
)
)
after the process I want to get: 经过这个过程,我想得到:
Array
(
[0] => Array
(
[0] => 4 //ID
[1] => 332 //Class
[2] => 'd' //Name
)
[1] => Array
(
[0] => 5 //ID
[1] => 332 //Class
[2] => 'z' //Name
)
[2] => Array
(
[0] => 3 //ID
[1] => 7 //Class
[2] => 'v' //Name
)
[3] => Array
(
[0] => 1 //ID
[1] => 88 //Class
[2] => 'a' //Name
)
[4] => Array
(
[0] => 2 //ID
[1] => 88 //Class
[2] => 'b' //Name
)
)
I tried to use array_multisort with 2 fields, but it's not work. 我尝试将array_multisort与2个字段一起使用,但这是行不通的。 anyone have ideas? 有人有主意吗?
Thank 谢谢
This isn't really what I would refer to as grouping, although I can see why you would think of it that way. 虽然我可以理解为什么您会这样考虑,但实际上这并不是我所说的分组。 Really this is just a sort with a hierarchical set of criteria rather than just a single criterion. 确实,这只是一种具有一组层次结构的条件,而不是仅一个条件的排序。 You sort by Parent ID, then use ID to break ties. 您按父ID排序,然后使用ID打破平局。 It can be done with usort
. 可以用usort
完成。
usort($data, function($a, $b) {
// compare group ID
return ($a[2] - $b[2]) ?: ($a[0] - $b[0]);
// compare ID if group ID is equal
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.