按二维数组的列之一对二维数组进行排序
[
1 => ['id' => 1, 'sort' => 1],
3 => ['id' => 3, 'sort' => 3],
2 => ['id' => 2, 'sort' => 2],
]
如何对其进行排序,以便使用内部“排序”键重新排序? 期望的结果:
[
1 => ['id' => 1, 'sort' => 1],
2 => ['id' => 2, 'sort' => 2],
3 => ['id' => 3, 'sort' => 3],
]
[
1 => ['id' => 1, 'sort' => 1],
3 => ['id' => 3, 'sort' => 3],
2 => ['id' => 2, 'sort' => 2],
]
How do I sort it so that it's re-ordered using the inner 'sort' key?
Desired result:
[
1 => ['id' => 1, 'sort' => 1],
2 => ['id' => 2, 'sort' => 2],
3 => ['id' => 3, 'sort' => 3],
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将
usort
与此比较函数一起使用:或者使用
array_multisort
以及用于排序顺序的附加键值数组:此处
array_map
与 匿名函数 用于构建 sort 值的数组,该数组用于对数组值本身进行排序。这样做的好处是,每对值都需要调用 np 比较函数。You can use
usort
with this comparison function:Or you use
array_multisort
with an additional array of key values for the sort order:Here
array_map
with the anonymous function is used to build an array of the sort values that is used to sort the array values itself. The advantage of this is that there is np comparison function that needs to be called for each pair of values.像这样的东西:
Something like this:
像这样的东西:
Something like this:
实现最新语法(自 PHP7.4 起),使用数组函数语法和 spaceship 运算符。将
$a
写在左侧,将$b
写在右侧即可进行 ASC 排序。反之$b <=> $a
给出 DESC 排序。uasort()
保留原始的第一级键(对于数字键,usort()
不会执行此操作,array_multisort()
也不会执行此操作)。代码:(演示)
Implement the latest syntax (since PHP7.4) use array function syntax with the spaceship operator. Writing
$a
on the left and$b
on the right gives an ASC sort. Conversely$b <=> $a
gives a DESC sort.uasort()
preserves the original first level keys (whichusort()
will not do andarray_multisort()
will not do with numeric keys).Code: (Demo)