![](/img/trans.png)
[英]PHP : How to delete elements from one associative array using another associative array
[英]PHP: How to delete rows from an associative array
我有一個關聯數組,其中鍵是日期時間類型數據(間隔為 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;
}
}
);
在這里工作小提琴。
而不是使用foreach()
,您可以使用for()
並使用持續時間來跳過不需要的條目。 結果被放入$slots
。
基本上,循環插槽中的時間,如果設置了持續時間,則將循環計數器增加約會的長度(持續時間/15 並使用ceil()
將其四舍五入)...
$row = ["09:00" => (object)["duration" => 40],
"09:15" => "",
"09:30" => "",
"09:45" => "",
"10:00" => (object)["duration" => 60],
"10:15" => "",
"10:30" => "",
"10:45" => "",
"11:00" => "",
"11:15" => "",
"11:30" => "",
"11:45" => (object)["duration" => 45]
];
$slots = [];
$times = array_keys($row);
for ( $i = 0; $i < count($times); $i++ ) {
$appointment = $row[$times[$i]];
$slots[$times[$i]] = $appointment;
if ( $appointment->duration ?? 0 > 0 ) {
$i += ceil($appointment->duration / 15);
}
}
print_r($slots);
有了測試數據,這給出了......
(
[09:00] => stdClass Object
(
[duration] => 40
)
[10:00] => stdClass Object
(
[duration] => 60
)
[11:15] =>
[11:30] =>
[11:45] => stdClass Object
(
[duration] => 45
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.