PHP对象数组-按属性分组

PHP对象数组-按属性分组,php,grouping,Php,Grouping,我很难按属性对对象数组进行分组。我找不到这个问题的好答案;可能是我累了;可能是我错过了一些重要的东西。 无论如何,我已经创建了一个Employee类,其中包含Employee的对象。包括姓名、电子邮件、电话和部门。 我想按部门对我的员工进行分组。因此,如果我打印出我的数组,销售人员中的每个人都将分组在一起 下面是它现在的样子: $employees = array(); while ($loop->have_posts() ) : $loop->the_post();

我很难按属性对对象数组进行分组。我找不到这个问题的好答案;可能是我累了;可能是我错过了一些重要的东西。 无论如何,我已经创建了一个Employee类,其中包含Employee的对象。包括姓名、电子邮件、电话和部门。 我想按部门对我的员工进行分组。因此,如果我打印出我的数组,销售人员中的每个人都将分组在一起

下面是它现在的样子:

 $employees = array();
     while ($loop->have_posts() ) : $loop->the_post();

    $data = array(
    'name' => get_post_meta(get_the_ID(), 'prefix_name', true),
    'email' => get_post_meta(get_the_ID(), 'prefix_mail', true),
    'phone' => get_post_meta(get_the_ID(), 'prefix_phone', true),
    'department' => get_post_meta(get_the_ID(), 'prefix_department', true)
    );
    array_push($employees, new Employee($data));
endwhile;
以及雇员类别:

class Employee
{

public $name;
public $email;
public $phone;
public $department;


public function __construct(Array $params = array()){
    if(count($params)){
        foreach($params as $key => $value) {
            $this->$key = $value;
        }
    }
}

}

$employees
需要是一个关联数组,将各个部门作为其键

像这样:

$employees = array();
while ($loop->have_posts() ) : $loop->the_post();

    $data = array(
      'name' => get_post_meta(get_the_ID(), 'prefix_name', true),
      'email' => get_post_meta(get_the_ID(), 'prefix_mail', true),
      'phone' => get_post_meta(get_the_ID(), 'prefix_phone', true),
      'department' => get_post_meta(get_the_ID(), 'prefix_department', true)
    );

    // Check if there is already an index for this department, or create it
    if(!isset($employees[$data['department']])) {
        $employees[$data['department']] = array();
    }

    // Assign the employee object to that key (department)
    $employees[$data['department']][] = new Employee($data));

endwhile;

你能告诉我们你试过什么吗?告诉我们你被困在哪里了?非常感谢!啊,我想我需要一些新鲜空气。我怎么可能这么蠢?天哪,我觉得自己很愚蠢。非常感谢您的帮助,我将很快将其标记为已解决:)