什么是基于值将多维数组拆分为一组数组的有效方法?

时间:2011-09-07 13:18:11

标签: php arrays multidimensional-array

我有一个多维数组,如下所示:

Array (

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

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

如何根据[name]的第一个字母排列/拆分此数组?

即。这个数组中有大约1,000个项目,我已经按[name]的字母顺序排序,但是我希望能够有以'A','B'等开头的组。

像这样,对于'A'和'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
       )
)

1 个答案:

答案 0 :(得分:4)

$split = array();
foreach ($array as $item) {
    $split[$item->name[0]][] = $item;
}