按第一级键对 3d 数组进行排序,然后按单独的第三级键对第二级进行排序
我有一个像这样的多维数组:
[
'user 1' => [
['item 4' => '11385'],
['item 2' => '144268'],
['item 1' => '65774'],
['item 9' => '98523'],
],
'user 5' => [
['item 8' => '239233'],
],
'user 2' => [
['item 4' => '53718'],
['item 1' => '154687'],
],
]
我需要做的就是首先按用户(第一级键)对数组进行排序,然后按项目(第三级键)升序排序。
期望的结果:
[
'user 1' => [
['item 1' => '65774'],
['item 2' => '144268'],
['item 4' => '11385'],
['item 9' => '98523'],
],
'user 2' => [
['item 1' => '154687'],
['item 4' => '53718'],
],
'user 5' => [
['item 8' => '239233'],
],
]
I have a multidimensional array like this:
[
'user 1' => [
['item 4' => '11385'],
['item 2' => '144268'],
['item 1' => '65774'],
['item 9' => '98523'],
],
'user 5' => [
['item 8' => '239233'],
],
'user 2' => [
['item 4' => '53718'],
['item 1' => '154687'],
],
]
What I need to do is to simply sort my array first by users (first level keys), then by items (third level keys) ascending.
Desired result:
[
'user 1' => [
['item 1' => '65774'],
['item 2' => '144268'],
['item 4' => '11385'],
['item 9' => '98523'],
],
'user 2' => [
['item 1' => '154687'],
['item 4' => '53718'],
],
'user 5' => [
['item 8' => '239233'],
],
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ksort
按键排序输出:(演示)
ksort
sorts by the keyOutput: (Demo)
使用
usort()
然后创建两个比较函数并排序你的数组一一使用它们。Use
usort()
then create two comparison functions and sort your array using them one after one.要按第一级键排序,然后按每个子数组中 firat 元素的键排序,请调用 ksort(),然后按单个元素的键在每组数据中排序。
代码:(演示)
或者使用
array_myltisort()
来减少总迭代函数调用: (演示)To sort by first level keys, then by the key of the firat element in each subarray, call
ksort()
then sort within each set of data by the lone element's key.Code: (Demo)
Or with
array_myltisort()
for fewer total iterated function calls: (Demo)