doulai8405 2014-08-05 17:59
浏览 75
已采纳

在该数组中按值循环数组分组索引(PHP)

I wish to create a list of items from an array, grouped by a value within that array.

Take this array:

$people = array(
    0 => array(
         "Forename" => "Jim",
         "Surname"  => "Smith"
    ),
    1 => array(
         "Forename" => "Mike",
         "Surname"  => "Johnson"
    ),
    2 => array(
         "Forename" => "Kim",
         "Surname"  => "Smith"
    ),
    3 => array(
         "Forename" => "Paul",
         "Surname"  => "Jones"
    )
);

Specifically I'd like to run a foreach on $people, grouping them by unique surname. i.e. the desired output would be:

<select>
    <optgroup label="Smith">
        <option>Jim</option>
        <option>Kim</option>
    </optgroup>
    <optgroup label="Johnson">
        <option>Mike</option>
    </optgroup>
    <optgroup label="Jones">
        <option>Paul</option>
    </optgroup>
</select>

I'm struggling to come up with anything vaguely efficient and the Google gods aren't watching over me today :( What's the best approach for such a use-case in PHP?

  • 写回答

3条回答 默认 最新

  • dpbe81245 2014-08-05 18:03
    关注
    $surnames = array();
    foreach($people as $person) {
        $surnames[$person['surname']][] = $person;
    }
    

    This code stores all persons in an array grouped by their surnames.

    The resulting array:

    array(
     'smith' => array(
       0 => array(
         "Forename" => "Jim",
         "Surname"  => "Smith"
       ),
       1 => array(
         "Forename" => "Kim",
         "Surname"  => "Smith"
       )
     ),
     'jones' => array(
       0 => array(
         "Forename" => "Paul",
         "Surname"  => "Jones"
       )
     )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?