我很难按属性将一系列对象分组。我找不到一个很好的答案。可能是我很累;可能是我错过了这里的重要事物。 无论如何 - 我创建了一个员工班级持有员工的对象。包括姓名,电子邮件,电话和部门。 我想按部门将我的员工数组分组。因此,如果我打印出阵列,销售中的每个人都会分组在一起。
现在的外观:
$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;