phparraysmultidimensional-arraygroupingsub-array

Group an array of objects by property


I am having a difficult time grouping an array of objects by a property. I couldn't find a good answer on this one; might be that I'm tired; might be that I missed out on something essential here. Anyways - I have created an Employee class holding objects of employees. Including name, email, phone and department. I would like to GROUP my array of employees by their department. So if I print out my array, everybody on sales will be grouped together.

Heres what it looks like now:

 $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;

And the Employee class:

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;
            }
        }
    }
}

Solution

  • $employees would need to be an associative array, having the individual departments as it's keys.

    Like this:

    $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;