PHP分裂阵列成组基于一个字段的值 [英] PHP splitting arrays into groups based on one field's value

查看:122
本文介绍了PHP分裂阵列成组基于一个字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含姓名和其他细节的数组的数组,按字母顺序排列。每个阵列包括与名称相关联的第一个字母。

I have an array containing arrays of names and other details, in alphabetical order. Each array includes the first letter associated with the name.

Array
(
    [0] => Array
        (
            [0] => a
            [1] => Alanis Morissette
        )

    [1] => Array
        (
            [0] => a
            [1] => Alesha Dixon
        )
    [2] => Array
        (
            [0] => a
            [1] => Alexandra Burke
        )

    [3] => Array
        (
            [0] => b
            [1] => Britney Spears
        )

    [4] => Array
        (
            [0] => b
            [1] => Bryan Adams
        )
)

我想显示它们由首字母组合,如:

I'd like to display them grouped by that first initial, eg:

A
-
Alanis Morissette
Alesha Dixon
Alexandra Burke

B
-
Britney Spears
Bryan Adams

etc...

这是在所有可能的?

Is this at all possible?

推荐答案

您可以将它们很容易,即使他们没有排序:

You can group them easily, even if they aren't sorted:

$groups=array();
foreach ($names as $name) {
    $groups[$name[0]][] = $name[1];
}

您甚至不需要到第一个初始存储组他们:

You don't even need to store the first initial to group them:

$names = array(
  'Alanis Morissette',
  'Alesha Dixon',
  'Alexandra Burke',
  'Britney Spears',
  'Bryan Adams',
  ...
);

$groups=array();
foreach ($names as $name) {
    $groups[$name[0]][] = $name;
}

这篇关于PHP分裂阵列成组基于一个字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆