A co-worker was working on some stuff dealing with creating collections of objects within an array so I decided to play around with the idea. Basically, you start with a big array filled of objects and the objective is to create smaller arrays of similar objects. In this case we want collections of person objects who names are the same. Here is what I came up with:

span class=”st0″>”‘bob’‘bob’‘moses’‘joey’‘bob’‘joey’‘bob’‘moses’‘joey’‘joey’// loop until there are no person left in array
// new collection and insert first person from array
// now remove person from array since already in collection
// loop through each person in array
// check if there is a match
// add person to this collection
                        $collection[] = $persons[$x];

                        // pop if last item
// move back since array position gets deleted, else will skip over next index

And the result is:


You start with 1 big array and end up with, in this case, 3 arrays of person whos names are ‘bob’, then ‘moses’, and finally ‘joey’.

Tags: , ,