Iam很难用属性对一组对象进行分组。我无法在这个问题上找到一个好的答案;可能是我累了;可能是我错过了这里必不可少的东西。 无论如何 - 我创建了一个包含员工对象的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;
}
}
}
}
答案 0 :(得分:1)
$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;