簡體   English   中英

PHP對象數組-按屬性分組

[英]PHP array of objects - group by property

我很難按屬性將對象數組分組。 我找不到一個好的答案。 可能是我累了; 可能是因為我錯過了一些重要的東西。 無論如何-我創建了一個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;

和Employee類:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM