phparraysobjectmultidimensional-arraygrouping

Split an array of objects into groups of objects initialized by any encountered object of a specific instance


I have an array that looks like this:

array(
    0 => object //ticket,
    1 => object //user,
    2 => object //employee,
    3 => object //ticket,
    4 => object //user
    5 => object //ticket,
    6 => object //employee
);

From this you can see that the ticket object is always there, whereas the employee and user objects are each optional. What I'd like to do is loop through them and organize them like so:

array(
    [0] => array(
        [0] => object //ticket,
        [1] => object //user,
        [2] => object //employee,
    )
)

What I'm having trouble with is since the user and employee are optional I'm not sure how to correctly index based on the above model since occasionally I will hit one that doesn't have an employee or user (in the case that it doesn't, I'd want that index to be null). Any ideas?

EDIT: Example:

for ($i = 0; $i < count($result); $i++) {
    if ($result[$i] instanceof Ticket) {
        continue;
    } else {
        $newResult[$i][] = $result[$i]; //maybe I'm brainfarting, but cannot figure how to identify the last ticket index
    }
}

Solution

  • This is similar to your own answer, but doesn't require reindexing $newResult when it's done.

    $newIndex = -1;
    $newResult = array();
    foreach ($result as $object) {
        if ($object instanceof Ticket) {
            $newResult[] = array($object);
            $newIndex++;
        } else {
            $newResult[$newIndex][] = $object;
        }
    }
    

    However, your original question mentioned setting the unused elements of the subarrays to null. Your answer doesn't do that, so I didn't either.