Home > Net >  Retrieve arrays based on the conditions met
Retrieve arrays based on the conditions met

Time:05-21

I have a set of arrays. I wanted to retrieve the nearest date that is unavailable.

For example, I provided a date 01-05-2022. The result I get should be the room_id 4 since it's the nearest date.

If I provided a date 05-05-2022, the result will be room_id 6.

$array = [
   0 => [
     "room_id" => "1",
     "date" => "01-05-2022"
     "available" => "A"
   ],
   1 => [
     "room_id" => "2",
     "date" => "02-05-2022"
     "available" => "A"
   ],
   2 => [
     "room_id" => "3",
     "date" => "03-05-2022"
     "available" => "A"
   ],
   3 => [
     "room_id" => "4",
     "date" => "04-05-2022"
     "available" => "U"
   ],
   4 => [
     "room_id" => "5",
     "date" => "05-05-2022"
     "available" => "A"
   ],
   5 => [
     "room_id" => "6",
     "date" => "06-05-2022"
     "available" => "U"
   ],
]

This is how I did it but I don't get any results:

$nextUnavailableDate = [];
foreach ($array as $item) {
  $selectedDate = date('Y-m-d', strtotime("01-05-2022"));
  $itemDate = date('Y-m-d', strtotime($item['date']));
  
  if ($selectedDate < $itemDate) {
    $q = array_filter($item, function($value) {
        return $value['availability'] === 'U';
    });

    if ($q) {
        $nextUnavailableDate = $q;
    }
  }
}

Any help is appreciated. Any explanation is appreciated too as I'm still learning PHP. Thanks!

CodePudding user response:

Can you try this one?

$nextUnavailableDate = [];
foreach ($array as $item) {
  $selectedDate = date('Y-m-d', strtotime("01-05-2022"));
  $itemDate = date('Y-m-d', strtotime($item['date']));
  
  if ($selectedDate < $itemDate) {
    // retrieving all the `availability` keys that has the value of U
    // will give you a list of availability value of U results
    if ($item['availability'] === 'U') {
        $nextUnavailableDate[] = $item;
    }
  }
}

// will then try to retrieve the first array since it's the nearest value that you requested
var_dump(array_shift(array_values($nextUnavailableDate)));
  •  Tags:  
  • php
  • Related