我有一个laravel系列,我按照属性' name'排序。
{
"0":{"id":2,"name":"1","days":["2017-04-06","2017-04-07"]},
"1":{"id":3,"name":"2","days":["2017-04-08","2017-04-09"]},
"2":{"id":4,"name":"3","days":["2017-04-10","2017-04-11"]},
"6":{"id":10,"name":"4","days":["2017-04-12","2017-04-13"]},
"3":{"id":5,"name":"5","days":["2017-04-14","2017-04-15"]},
"4":{"id":6,"name":"6","days":["2017-04-16","2017-04-17"]},
"5":{"id":7,"name":"7","days":["2017-04-18","2017-04-19"]}
}
但是这个集合的索引没有改变。索引现在是0,1,2,6,3,4,5。是否可以按排序集合的顺序重新索引集合?
所以我想拥有的是:
{
"0":{"id":2,"name":"1","days":["2017-04-06","2017-04-07"]},
"1":{"id":3,"name":"2","days":["2017-04-08","2017-04-09"]},
"2":{"id":4,"name":"3","days":["2017-04-10","2017-04-11"]},
"3":{"id":10,"name":"4","days":["2017-04-12","2017-04-13"]},
"4":{"id":5,"name":"5","days":["2017-04-14","2017-04-15"]},
"5":{"id":6,"name":"6","days":["2017-04-16","2017-04-17"]},
"6":{"id":7,"name":"7","days":["2017-04-18","2017-04-19"]}
}
我尝试使用$collection->values()
。但后来我离开了:
[
{"id":2,"name":"1","days":["2017-04-06","2017-04-07"]},
{"id":3,"name":"2","days":["2017-04-08","2017-04-09"]},
{"id":4,"name":"3","days":["2017-04-10","2017-04-11"]},
{"id":10,"name":"4","days":["2017-04-12","2017-04-13"]},
{"id":5,"name":"5","days":["2017-04-14","2017-04-15"]},
{"id":6,"name":"6","days":["2017-04-16","2017-04-17"]},
{"id":7,"name":"7","days":["2017-04-18","2017-04-19"]}
]
答案 0 :(得分:3)
作为Laravel Collections docs says,您可以对集合使用 values()来重置索引:
$resetedIndexesCollection = $yourcollection->values();
values方法返回一个重置为的新集合 连续整数。
如果你的情况不合适,因为你没有集合,你有一个json,首先你需要json_decode
创建一个array
,然后收集数组,现在你有了一个集合,你可以应用values()方法来重置索引,如下所示:
collect(json_decode('{
"0":{"id":2,"name":"1","days":["2017-04-06","2017-04-07"]},
"1":{"id":3,"name":"2","days":["2017-04-08","2017-04-09"]},
"2":{"id":4,"name":"3","days":["2017-04-10","2017-04-11"]},
"3":{"id":10,"name":"4","days":["2017-04-12","2017-04-13"]},
"4":{"id":5,"name":"5","days":["2017-04-14","2017-04-15"]},
"5":{"id":6,"name":"6","days":["2017-04-16","2017-04-17"]},
"6":{"id":7,"name":"7","days":["2017-04-18","2017-04-19"]}
}'))->values();
结果如下:
Collection {#287 ▼
#items: array:7 [▼
0 => {#288 ▼
+"id": 2
+"name": "1"
+"days": array:2 [▶]
}
1 => {#407 ▼
+"id": 3
+"name": "2"
+"days": array:2 [▶]
}
2 => {#408 ▼
+"id": 4
+"name": "3"
+"days": array:2 [▶]
}
3 => {#409 ▼
+"id": 10
+"name": "4"
+"days": array:2 [▶]
}
4 => {#410 ▼
+"id": 5
+"name": "5"
+"days": array:2 [▶]
}
5 => {#411 ▼
+"id": 6
+"name": "6"
+"days": array:2 [▶]
}
6 => {#412 ▼
+"id": 7
+"name": "7"
+"days": array:2 [▶]
}
]
}
答案 1 :(得分:0)
collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
请查看此处的文档:https://laravel.com/docs/5.4/collections#method-sort