php - PHP:如何从关联数组中删除行
问题描述
我有一个关联数组,其中键是日期时间类型数据(间隔为 15 分钟)
array:37 [▼
"09:00" => Appointment {
#attributes: array:10 [▼
"id" => 1135
"startDateTime" => "2019-11-19 09:00:00"
"endDateTime" => "2019-11-19 09:45:00"
"duration" => 45
]
}
"09:15" => "" // I want to delete this row -> 15 minutes
"09:30" => "" // I want to delete this row -> 30 minutes end of the appointment
"09:45" => ""
"10:00" => Appointment {...duration => 60 ...}
"10:15" => "" // I want to delete this row -> 15 minutes
"10:30" => "" // I want to delete this row -> 30 minutes
"10:45" => "" // I want to delete this row -> 45 minutes
"11:00" => "" // I want to delete this row -> 60 minutes end of the appointment
"11:15" => ""
"11:30" => ""
"11:45" => "" Appointment {...duration => 15 ...}
...
]
该数组将提供一个表格,因此我想根据每个约会的持续时间删除后续行。我需要它,因为我想将约会跨越几行:
<td class="the-appointment" rowspan="{{ $appointment->duration / 15 }}">...
因此我需要从数组中消除后续行。
我这样做了:
$index = -1;
foreach ($row as $key => $appointment) {
if ($appointment) {
$loops = $appointment->duration / 15;
}
for ($i = 1; $i < $loops; $i++) {
unset($row[$index + 1]);
$index++;
}
}
array_push($calendar, $row);
但由于它是一个关联数组,我无法获得循环的索引。有没有更聪明的方法来做到这一点?
解决方案
一些代码开始:
$duration = 0;
// I suggest to use array_filter and track `$duration` on each loop
$filtered = array_filter(
$apps,
function ($apm) use (&$duration) {
if ($duration === 0) {
if (!empty($apm->duration)) {
$duration = $apm->duration - 15;
return true;
} else {
return true;
}
} else {
$duration -= 15;
return false;
}
}
);
在这里工作小提琴。
推荐阅读
- typescript - 升级到 Typescript 2.9.1 后出现“TS2300: Duplicate identifier 'Account'”错误
- swift - 使用 imageView 作为具有 preferLargeTitles 的导航栏的标题
- javascript - 如何在javascript中有条件地发送异步请求作为预请求?
- git - 即使没有发生错误,git pull 也不起作用
- msbuild - 如果我有对某些 dll 的引用,请在 csproj 文件中定义常量
- php - 宾果游戏 - 如何点击/显示选择
- html - 复选框和同级选择器
- angular - 如何通过 AnimationPlayer 或 AnimationReferenceMetadata 提供无限动画(需要替代方案)
- ios - 如果在 NSPredicate 中使用 OR,则无法成功过滤结果
- php - Foreach 循环多次插入相同的数据