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


Compare two multidimensional arrays and unset matched elements

>更新:在我得到回复后,我意识到我已经尝试使用数据库查询来解决这个问题,所以我在这里写了一篇更详细的文章

原文:我想比较两个多维数组并摆脱与特定标准匹配的元素。我知道我将不得不用一些键遍历数组然后取消设置,但我似乎无法正确完成。

这两个阵列是$all存储所有可用房间及其床和$reserved,其中只有保留的房间和保留的床。

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

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

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

所以最后,当我循环遍历$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')));

使用嵌套循环:

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()调用修改原始数组。

演示