简体   繁体   中英

Filter into a multidimensional array in PHP

I have this array:

$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')
    )
);

How can I loop into this to get items with the first item in days[] equal to the current date or the date I want ?

For example, if we are the 2016-11-23 , I need to get the first item into the array which is:

$bookings[] = array(
    'booking_id' => '1', 
    'client_firstname' => 'Gareth', 
    'days' => array(
        array('day_id' => '2016-11-23,2016-11-24', 'room_id' => '2')
    )
);

because into the days array, it starts with the date I search 2016-11-23 .

Thanks.

Your requirements are a little unclear, but array_filter is what you want. It takes a callback function which you can use to interrogate each item in the outer array. If you return something trueish from this function, the array item is included in the filtered array. If you return something falseish, the array item is excluded from the filtered array.

Rough example below, based on what I think you're asking for. If it's wrong, it should give you the right idea to tweak it.

<?php
$filtered = array_filter($bookings, function($item) {
        $days = explode(',', $item['days'][0]['day_id']);

        return $days[0] == '2016-11-23';
});

var_dump($filtered);

I suggest you also add some sanity checking to this to avoid errors in the event of bad data.

This will get the booking array matching the date you provide

<?php
    $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']))){
             $bookings_[]  = $b;
           }
        }
    }
    var_dump($bookings_);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM