Question

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?

Was it helpful?

Solution

It's pretty hard to work on your structure without looping it.. Maybe you can simplify it like this..

$new_arr = array();
foreach($arr as $arr1)
{
    $new_arr[$arr1['id']] = array_slice($arr1,1);
}
print_r($new_arr);

Demonstration

Eventhough this can be achieved using array functions , but performance will not be that good when compared to a foreach

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top