For a game, I have a collection of 'houses' and each house belongs to a 'city'. I want to separate this collection (it's an array) based on this city, so each city will have its own array of houses. I found no built-in array function to do this (such as an array_split
taking a callback), so how would I do this?
I thought on iterating over every element of the array, but this seems very very slow. The houses are already all ordered by city id, so I may use some splitting function if I get the exact position where the city id changes.
Houses in the array are stored like this:
array(3) {
["id"]=> string(1) "1",
["name"]=> string(13) "Example House",
["city_id"]=> string(1) "1",
}
Cities are just a number representing them, not another object.
I expect the out to be something like:
array(n) {
[1]=> array(o) {
["id"]=> string(1) "1",
["name"]=> string(13) "Example House",
}, ...
}
Is it the correct manner to do it? Is there any builtin function or better algorithm?