简体   繁体   English

在PHP中过滤为多维数组

[英]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 ? 我怎样才能循环到这个以获取具有days[]第一项的项目等于当前日期或我想要的日期?

For example, if we are the 2016-11-23 , I need to get the first item into the array which is: 例如,如果我们是2016-11-23 ,我需要将第一个项目放入数组中:

$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 . 因为在days数组中,它从我搜索2016-11-23的日期开始。

Thanks. 谢谢。

Your requirements are a little unclear, but array_filter is what you want. 您的要求有点不清楚,但array_filter就是您想要的。 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_);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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