比较两个多维数组和未设置的匹配元素

时间:2016-02-19 23:11:45

标签: php arrays multidimensional-array

更新:在收到回复之后,我意识到我应该尝试使用数据库查询解决这个问题,所以我写了a more detailed post here

原始帖子: 我想比较两个多维数组,摆脱符合某个标准的元素。我知道我将不得不用一些键循环遍历数组然后取消设置,但我似乎无法正确地完成它。

这两个阵列是$all,它存放了所有可用的房间及其床和$reserved,其中只有预留房间和预留床位。

我想循环浏览所有预订并获取位置$reservations[x][0]的房间标题,其中x是当前查看的预订,并将其与$all[a][0]中所有元素进行比较,其中a是当前查看的房间。

那么当我发现$all[0][0] =>的值时'Luxury Room'与$reservations[0][0] =>匹配'豪华房'我将查看床位和y位置的床位,其中y是当前查看的床位代码$reservations[x][1][y],并将其与匹配房间的所有可用床位进行比较,以及$all[0][1][b]其中b是所有可用的房间。

当我发现$all[0][1][1] =>'xx2'的值与$reservations[0][1][0] =>'xx2'中的值匹配时,我将取消设置索引0 {{3}来自$all

所以最后我将循环遍历$all数组,并将每个元素的索引[0]列为索引1上数组的标题和元素作为床,我只会睡觉'xx2'可用于“豪华房”

//$all is an array where index 0 is an array   
$all = array( 0=>array(
                    //index 0 has value 'Luxury Room' (room title)
                    0=>'Luxury Room',
                    //index 1 is an array
                    1=>array(
                            //where index 0 has value 'xx1' (bed code)
                            0=>'xx1',
                            //where index 1 has value 'xx2' (bed code)
                            1=>'xx2')),
            //again index 1 is an array etc. just as above...
            1=>array(
                    0=>'Cheap Room',
                    1=>array(
                            0=>'zz1',
                            1=>'zz2',
                            2=>'zz3',
                            3=>'zz4')));

$reserved = array( 0=>array(
                    0=>'Luxury Room',
                    1=>array(0=>'xx2')));

1 个答案:

答案 0 :(得分:1)

使用嵌套循环:

foreach ($all as &$room) {
    foreach ($reserved as $r) {
        if ($room[0] == $r[0]) { // same types of room
            foreach ($room[1] as $i => $code) {
                if (in_array($code, $r[1])) {
                    unset($room[1][$i]);
                }
            }
        }
    }
    $room[1] = array_values($room[1]); // Reset array indexes
}

$all循环使用迭代变量的引用,以便unset()调用修改原始数组。

DEMO

相关问题