4

I have a multidimensional array like the following:

Array (

       [0] => stdClass Object (
                [name] => StackOverflow
                [image] => CanHelp.jpg
       ) 

       [1] => stdClass Object (
                [name] => AnotherObject
                [image] => SecondImage.jpg
       ) 
)

How can I arrange/split this array into groups based on the first letter of [name]?

i.e. There are about 1,000 items in this array, which I have already ordered alphabetically by [name], however I want to be able to have groups that begin with 'A', 'B', etc.

Like this, for 'A' and 'S':

Array (

       [0] => stdClass Object (
                [name] => AnotherObject
                [image] => SecondImage.jpg
       ) 

       [1] => stdClass Object (
                [name] => AndAnother
                [image] => notImportant.jpg
       )
)

Array (

       [0] => stdClass Object (
                [name] => StackOverflow
                [image] => CanHelp.jpg
       )
)
0

1 Answer 1

4
$split = array();
foreach ($array as $item) {
    $split[$item->name[0]][] = $item;
}
Sign up to request clarification or add additional context in comments.

4 Comments

almost perfect! thanks! one more thing - is it possible to group non-alphabetic chars into one array? e.g. [0]? including numbers and other chars.
@samb Sure. The logic is simple enough to extend. :P
foreach ($array as $item) { if ( preg_match('/[a-z]/', $item->name[0]) ) $split[$item->name[0]][] = $item; else $split['other'][] = $item; }
@roselan cheers - make it '/[A-Za-z]/' and it's what I wanted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.