'Remove array if meets certain conditions
I'm trying to work out how I can remove all timestamps which have a certain reservation id after them. Currently I can unset only based on timestamp and not check whether reservation id is there. This is part of the php code snippet:
$pending_prep_dates_array = array();
$check_in_date = get_post_meta( $resID, 'reservation_checkin_date', true );
$check_out_date = get_post_meta( $resID, 'reservation_checkout_date', true );
$check_in_prep = new DateTime($check_in_date);
$check_in_prep->sub(new DateInterval('P2D')); // P1D means a period of 1 day
$check_in_final = $check_in_prep->getTimestamp();
$check_out_prep = new DateTime($check_out_date);
$check_out_prep->add(new DateInterval('P2D')); // P1D means a period of 1 day
$check_out_final = $check_out_prep->getTimestamp();
for ($currentDate = $check_in_final; $currentDate <= $check_out_final; $currentDate += (86400)) {
$Store = $currentDate;
unset($pending_prep_dates_array[$Store]);
This is how it is stored in array in my database:
a:15{i:1652054400;i:8997;i:1652140800;i:8999;i:1652227200;i:8999;i:1652313600;i:8999;i:1652400000;i:8999;i:1652486400;i:8999;i:1652572800;i:8999;i:1651536000;i:8993;i:1651622400;i:8993;i:1651708800;i:8993;i:1651795200;i:8993;i:1651881600;i:8993;i:1651968000;i:8997;i:1651363200;i:8993;i:1651449600;i:8993;}
So to clarify, how can I only remove timestamps if reservation id is for example 8999?
Thanks
Solution 1:[1]
You can iterate through the data and build a new array with the ID(s) removed:
<?php
$raw = 'a:15:{i:1652054400;i:8997;i:1652140800;i:8999;i:1652227200;i:8999;i:1652313600;i:8999;i:1652400000;i:8999;i:1652486400;i:8999;i:1652572800;i:8999;i:1651536000;i:8993;i:1651622400;i:8993;i:1651708800;i:8993;i:1651795200;i:8993;i:1651881600;i:8993;i:1651968000;i:8997;i:1651363200;i:8993;i:1651449600;i:8993;}';
$data = unserialize($raw);
$ids_to_remove = [8999, 8993];
$data_with_id_removed = [];
foreach ($data as $timestamp => $id) {
if (in_array($id, $ids_to_remove))
continue;
$data_with_id_removed[$timestamp] = $id;
}
var_dump($data_with_id_removed);
Result (all timestamps with id 8999 and 8993 removed)
array(2) {
[1652054400]=>
int(8997)
[1651968000]=>
int(8997)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jacob Mulquin |
