这可能不是最有效的代码,但它可以满足您的需求。如果匹配中有多个条目$departments
,它将采用第一个条目的索引。如果没有找到匹配项,它将分配 value NULL
。
$classes = array(
array('Name' => 'BE1A', 'Department' => 'Emmen'),
array('Name' => 'Something', 'Department' => 'Another'),
array('Name' => 'Yet more', 'Department' => 'More'),
array('Name' => 'Yet more again', 'Department' => 'Nothing')
);
$departments = array(
array('Name' => '3 Receptie Emmen', 'code' => 'Emmen'),
array('Name' => 'Something else', 'code' => 'Another'),
array('Name' => 'More stuff', 'code' => 'More')
);
for($i=0; $i<count($classes); $i++) {
$arr = array_filter($departments, function($dpt) use($classes, $i) {
return ($dpt['code'] == $classes[$i]['Department']);
});
if(count($arr) > 0) {
reset($arr);
$classes[$i]['Department'] = key($arr);
}
else {
$classes[$i]['Department'] = NULL;
}
}
print_r($classes);
这将输出:
Array
(
[0] => Array
(
[Name] => BE1A
[Department] => 0
)
[1] => Array
(
[Name] => Something
[Department] => 1
)
[2] => Array
(
[Name] => Yet more
[Department] => 2
)
[3] => Array
(
[Name] => Yet more again
[Department] => -1
)
)
请注意,它使用闭包array_filter
,因此您至少需要 php 5.3 才能使用它。如果不这样做,则可以在比较函数中删除use($classes, $i)
并添加。global $classes, $i;