如何从关联数组中只打印一次部门名称
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从关联数组中只打印一次部门名称相关的知识,希望对你有一定的参考价值。
我想从关联的数组中打印部门。我想迭代数组并打印部门,但同一部门只能用逗号分隔一次。可以使用过滤器吗?或者可以使用Map完成吗?
$employee = array
(
0=>
array("employee_id"=>1, "firstName"=>"Zahir", "lastName"=>"Alam", "Age"=>25, "Company"=>"Switchme", "Role"=>"Developer", "Department"=>"Tech"
,"Head"=>
array("Id"=>3 , "Name"=>"Sourasis Roy")
)
,
1=>
array("employee_id"=>2, "firstName"=>"Amith", "lastName"=>"Manniken", "Age"=>25, "Company"=>"Switchme", "Role"=>"Developer", "Department"=>"Tech"
,"Head"=>
array("Id"=>3 , "Name"=>"Sourasis Roy")
)
,
2=>
array("employee_id"=>3, "firstName"=>"Sourasis", "lastName"=>"Roy", "Age"=>28, "Company"=>"Switchme", "Role"=>"CTO")
,
3=>
array("employee_id"=>4, "firstName"=>"Aditya", "lastName"=>"Mishra", "Age"=>29, "Company"=>"Switchme", "Department"=>"Tech", "Role"=>"CEO")
,
4=>
array("employee_id"=>5, "firstName"=>"Priti", "lastName"=>"Lata", "Age"=>24, "Company"=>"Switchme", "Role"=>"HR")
,
5=>
array("employee_id"=>6, "firstName"=>"Sumita", "lastName"=>"Nath", "Age"=>24, "Company"=>"Switchme", "Role"=>"HLA Head", "Department"=>"Crm")
,
6=>
array("employee_id"=>7, "firstName"=>"Tarini", "lastName"=>"Khanna", "Age"=>22, "Company"=>"Switchme", "Role"=>"Content Writer")
,
7=>
array("employee_id"=>8, "firstName"=>"Abhisek", "lastName"=>"Soni", "Age"=>23, "Company"=>"Switchme", "Role"=>"HLA", "Department"=>"Crm","Head"=>array("Id"=>5 , "Name"=>"Sumita Nath")
)
,
8=>
array("employee_id"=>9, "firstName"=>"Ankit", "lastName"=>"Pump", "Age"=>23, "Company"=>"Switchme", "Role"=>"HLA", "Department"=>"Crm"
,"Head"=>
array("Id"=>5 , "Name"=>"Sumita Nath")
)
,
9=>
array("employee_id"=>10, "firstName"=>"Pogo", "lastName"=>"Laal", "Age"=>23, "Company"=>"Switchme", "Role"=>"Designer")
,
10=>
array("employee_id"=>11, "firstName"=>"Sabina", "lastName"=>"Sekh", "Age"=>28, "Company"=>"Switchme", "Role"=>"HLA Head", "Department"=>"Crm")
,
11=>
array("employee_id"=>12, "firstName"=>"Sanjay", "lastName"=>"Poudal", "Age"=>24, "Company"=>"Switchme", "Role"=>"HLA Head", "Department"=>"Crm"
,"Head"=>
array("Id"=>10 , "Name"=>"Sabina Sekh")
)
,
);
for($i=0;$i<count($employee);$i++)
{
print_r(array_unique($employee[$i]['Department']));
}
预期输出应为Tech,Crm
答案
<?php
echo implode(",",array_unique(array_column($employee,'Department')));
使用array_column
过滤Department
列的值,并使用array_unique()
来获得Department
的唯一值。现在,只是implode()
他们基于,
。
以上是关于如何从关联数组中只打印一次部门名称的主要内容,如果未能解决你的问题,请参考以下文章
如何从 $.getJSON 调用以 print_r() 方式打印关联数组?