按一列的值对二维数组进行排序
我在思考如何做到这一点时遇到了一些问题。 我在 PHP 中有一个数组
array(131) {
["BLANF "]=>
array(3) {
["line_3"]=>
string(4) "3.92"
["line_1"]=>
string(1) "6"
["line_2"]=>
string(2) "14"
}
["BLOOH "]=>
array(3) {
["line_3"]=>
string(4) "2.00"
["line_1"]=>
string(1) "20"
["line_2"]=>
string(1) "6"
}
}
,需要根据 line_1 的值进行排序。
I'm having some problems wrapping my head around how to do this.
I have an array in PHP
array(131) {
["BLANF "]=>
array(3) {
["line_3"]=>
string(4) "3.92"
["line_1"]=>
string(1) "6"
["line_2"]=>
string(2) "14"
}
["BLOOH "]=>
array(3) {
["line_3"]=>
string(4) "2.00"
["line_1"]=>
string(1) "20"
["line_2"]=>
string(1) "6"
}
}
That I need to sort based on the value of line_1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须为数组创建一个自定义比较函数,并将其与
uasort()
维护数组的索引。以下是如何使用
uasort()
按line_1
排序...更改为按嵌套数组中的任何其他键排序很简单。实时示例
(我更改了
line_1
数字,以便排序实际上做了一些事情)在这种情况下,PHP 会为您处理类型,但您应该注意您有字符串并将它们转换为数字的事实。如果您不确定会发生什么,请将字符串转换为浮点数或整数。这很重要,因为 PHP 可以使用比较运算符按字母顺序比较字符串....所以,如果字母或逗号或其他内容有可能潜入您的数组值,那么您可以 类型转换 为 int (
(int) $a["line_1"]
) 或 float ((float) $a["line_1"]
)。You have to create a custom comparison function for your array and employ it with
uasort()
to maintain the indices of the array.Here is how you can use
uasort()
to sort byline_1
... It's simple to change to sort by any other key in the nested array.Live Example
(I changed the
line_1
numbers so that the sort actually does something)In this case PHP will juggle the types for you, but you should watch out for the fact that you have strings and are converting them to numbers. If you're not sure what will happen then cast the strings to floats or ints. This is important since, PHP can compare strings alphabetically with the comparison operators.... so, if there's any chance that a letter or comma or something can sneak into your array value then you can type cast to an int (
(int) $a["line_1"]
) or a float ((float) $a["line_1"]
).通过提供比较回调函数来使用
uasort
比较相应行的值。Use
uasort
by providing a comparison callback function that compares the values of the appropriate lines.