How to remove values ​​from Laravel array
P粉805535434
P粉805535434 2024-03-31 21:54:37
0
1
483

I'm trying to create a very basic day booking system that needs to return all dates in a range and then remove selected dates from that range. I tried the following code but realized this removes duplicates, which is fine, but I need to remove the date as well.

Can anyone suggest a good way to do this?

In the example below, I just want to see:

2022-04-03T00:00:00.000000Z

2022-04-04T00:00:00.000000Z

2022-04-05T00:00:00.000000Z

$start_date = "2022-04-01";
$end_date = "2022-04-05";

$datesToRemove = [
   '2022-04-01T00:00:00.000000Z',
   '2022-04-02T00:00:00.000000Z'
];

$range = Carbon::parse($start_date)->toPeriod($end_date)->toArray();
$available = array_unique(array_merge($range, $datesToRemove));
return $available;

P粉805535434
P粉805535434

reply all(1)
P粉186897465

To compare, the compared values ​​must have the same format. I decided to convert $datesToRemove to Carbon format. You can use nested loops and check using the PHP in_array() function.

$start_date = "2022-04-01";
$end_date = "2022-04-05";

$datesToRemove = [
"2022-04-01T00:00:00.000000Z",
"2022-04-02T00:00:00.000000Z"
];

$range = \Carbon\Carbon::parse($start_date)->toPeriod($end_date)->toArray();
$datesToRemove2 = [];
foreach($datesToRemove as $r) {
    $datesToRemove2[] = \Carbon\Carbon::parse($r);
}

$res = [];
foreach($datesToRemove2 as $index => $d1) {
    if(in_array($d1, $range)) {        
        unset($range[$index]);        
    }
}

return $range;

Output

{
  "2":"2022-04-03T00:00:00.000000Z",
  "3":"2022-04-04T00:00:00.000000Z",
  "4":"2022-04-05T00:00:00.000000Z"
}

mean

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template