uiklnmn uiklnmn - 12 days ago 9
PHP Question

Filter a multidimensional array in PHP

I have this array containing my bookings:

$bookings[] = array(
'booking_id' => '1',
'client_firstname' => 'Gareth',
'days' => array(
array('day_id' => '2016-11-23,2016-11-24', 'room_id' => '2'),
array('day_id' => '2016-11-25', 'room_id' => '4'),
array('day_id' => '2016-11-26,2016-11-27,2016-11-28', 'room_id' => '2'),
)
);
$bookings[] = array(
'booking_id' => '2',
'client_firstname' => 'James',
'days' => array(
array('day_id' => '2016-11-25,2016-11-26,2016-11-27,2016-11-28', 'room_id' => '5')
)
);
$bookings[] = array(
'booking_id' => '2',
'client_firstname' => 'Marco',
'days' => array(
array('day_id' => '2016-11-24', 'room_id' => '5')
)
);





Explication of the array:




  • The array shows the
    booking_id
    and the
    client_name
    .

  • The array
    days
    contains the schedule of the client in the hotel. Each array in this
    days
    array explains which days and in which room the client is. If I have more than one line, the client change room.






The wish



For a date I give, I need to get the bookings where into the
days array
the first date correspond to the date I give.




Example




  • Date I give is
    2016-11-25
    .

  • I need to get:

    $bookings[] = array(
    'booking_id' => '1',
    'client_firstname' => 'Gareth',
    'days' => array(
    array('day_id' => '2016-11-25', 'room_id' => '4')
    )
    );
    $bookings[] = array(
    'booking_id' => '2',
    'client_firstname' => 'James',
    'days' => array(
    array('day_id' => '2016-11-25,2016-11-26,2016-11-27,2016-11-28', 'room_id' => '5')
    )
    );






What I have try



$day_value = '2016-11-23';
$bookings_ = array();
foreach($bookings as $b){
foreach($b['days'] as $day){
if(in_array($day_value,explode(',',$day['day_id'][0]))){
$bookings_[] = $b;
}
}
}
print_r($bookings_);


But it returns me all the results into the bookings...

Could you please help me ?

Thanks.

Answer

What do you think is $day['day_id'][0]?

It's the first symbol of $day['day_id'] as latter is a string. So, nothing will be exploded by , in $day['day_id'][0]. And solution is to remove [0]:

foreach($bookings as $b){
    foreach($b['days'] as $day){
        if(in_array($day_value,explode(',',$day['day_id']))){
            // this string added:
            $b['days'] = $day;

            $bookings_[]  = $b;

            // btw, if your `$b['days']` has several elements
            // and in a couple of them there's a required date
            // then `$b` will be added to `$bookings_` several 
            // times, so probably you need `break`
            // break;
        }
    }
}
Comments