Tuesday, May 23, 2017

How to index my laravel collection by a property

I have a laravel collection which I have sorted by the property '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"]}
}  

However the index of this collection has not changed. The indexes are now 0,1,2,6,3,4,5. Is it possible to re-index the collection in the order of the sorted collection?

So what I would like to have is:

{
"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"]}
}  

I tried using $collection->values(). But then I am left with:

[
{"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"]}
]  



via Mazin

Advertisement