如何按嵌套在 PHP 数组中的元素对 PHP 数组进行排序?
我有一个如下所示的数组:
Array ( [0] => Array ( 'name' => "Friday" 'weight' => 6 ) [1] => Array ( 'name' => "Monday" 'weight' => 2 ) )
我想获取该数组中的最后一个值(“权重”),并使用它对主数组元素进行排序。因此,在这个数组中,我想对其进行排序,以便“星期一”元素出现在“星期五”元素之前。
I have an array like the following:
Array ( [0] => Array ( 'name' => "Friday" 'weight' => 6 ) [1] => Array ( 'name' => "Monday" 'weight' => 2 ) )
I would like to grab the last values in that array (the 'weight'), and use that to sort the main array elements. So, in this array, I'd want to sort it so the 'Monday' element appears before the 'Friday' element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
注意,如果您要排序的元素是像 .0534 和 .0353 这样的浮点数(例如百分比),那么您必须将两者都乘以 1000。坦率地说,不确定为什么......看来 usort 似乎比较整数价值观。
我花了一段时间才弄清楚其中一个...
以及 2 个可能不会立即显而易见的提示:
NOTE, if the element you are sorting on is a float like .0534 and .0353 (like for a percentage), then you have to multiply both by 1000. not sure why frankly... it appears that usort seems to compare the integer values.
took me awhile to figure that one out...
and 2 tips that may not be immediately obvious:
这是一个很酷的函数,可能会有所帮助:
将数组作为
$a
发送,将键作为$subkey
发送,并为$sort< 发送“asort”或“sort” /代码> 变量
Here's a cool function that might help:
Send in the array as
$a
the key as$subkey
and 'asort' or 'sort' for the$sort
variable同意 usort,我有时也使用 array_multisort (https://www.php. net/manual/en/function.usort.php) 示例 3,对数据库结果进行排序。
你可以做类似的事情:
输出:
Agree with usort, I also sometimes use array_multisort (https://www.php.net/manual/en/function.usort.php) example 3, sorting database results.
You could do something like:
Output:
如果您排序的字段是类似
title
name
的字符串,array_multisort + 自然排序 和 CaseInSensitivity 是可行的方法:
If the filed you sort by is string like
title
name
,array_multisort + Flags for Natural Sorting and CaseInSensitivity are the way to go:
您还可以使用匿名函数。
You can also use an anonymous function.
您可以将
usort
用作:You can use
usort
as:可以使用匿名函数来完成。
另外,如果您的“权重”是字符串,请使用其他返回之一(请参阅注释掉的行):
Can be done using an anonymous function.
Also if your 'weight' is a string use one of the other returns (see the commented out lines):