foreach ($array_leave_dates as $emp => $leave_type) {
foreach ($leave_type as $leave_dates) {
if($leave_type == 'Maternity Leave'){
unset($array_leave_dates[$leave_type]);
}
else{
echo $leave_dates[$row];
}
}
}
在这里,我们可以获取$ leave_dates,并希望删除或取消设置leave_type =='产假'。但不可能。请帮助指出上面代码中的错误。
答案 0 :(得分:1)
不确定您的数据源是什么样的:
<?php
// Remove the whole employee
$employees = array(
'emp1' => array('sick' => 'Mon - Tue'),
'emp2' => array('bun in oven' => '2016 - 2017'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp]);
}
}
}
print_r($employees);
// OR remove only 'Maternity' from the employee but keep everything else
<?php
$employees = array(
'emp1' => array('sick' => 'Mon - Tue', 'its friday and im not coming in' => 'Fri'),
'emp2' => array('bun in oven' => '2016 - 2017', 'sick' => 'Thu'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as $emp => $leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp][$leaveName]);
}
}
}
print_r($employees);
答案 1 :(得分:1)
查看//评论
foreach ($array_leave_dates as $emp => $leave_type) {
// you treat $leave_type as array here
foreach ($leave_type as $leave_dates) {
// you treat $leave_type as string here
// doesn't feel right
if($leave_type == 'Maternity Leave') {
// you are unsetting with a value
//unset($array_leave_dates[ --> $leave_type <-- ]);
// i assume you want to delete the key
unset($array_leave_dates[$emp]);
}
else{
// $row doesn't seem to exist, looks wrong from here
echo $leave_dates[$row];
}
}
}
答案 2 :(得分:0)
如果$leave_type
可以是"Maternity Leave"
,那么为什么要在该字符串值中搜索$leave_dates
?这个问题自然是反思的。从你有两个foreach
周期并且第二个嵌入第一个周期的事实让我认为$leave_type
不是你想象的那样。所以,我认为你有一个多维数组,其中外键是员工姓名或ID,内键是类型。例如:
array(
'John Doe' => array('Sickness' => array('a', 'b', 'c')),
'Mary Doe' => array('Sickness' => array('a', 'b', 'c'), 'Maternal Leave' => array('d', 'e'))
)
如果是这种情况,那么您需要修改周期:
foreach ($array_leave_dates as $emp => $leave) {
if ($leave['Maternity Leave']) {
unset($array_leave_dates[$emp]['Maternity Leave']);
}
}
如果您想要更通用的解决方案,那么这可能会对您有所帮助:
function removeByKey(&$arr, $k) {
if (arr[$k] !== null) {
unset arr[$k];
}
foreach($arr as $key => $value) {
if (is_array($value)) {
$arr[$key] = removeByKey($arr[$key], $k);
}
}
return $arr;
}