更新:在收到回复后,我意识到我应该尝试用数据库查询来解决这个问题,所以我编写了更详细的帖子在这里
原始文章:,我想比较两个多维数组,并去掉符合特定条件的元素。我知道我必须用一些键循环数组,然后取消设置,但我似乎不能正确地完成它。
这两个阵列分别是$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]=>’x2‘中的值匹配时,我将从$all中取消索引01。
因此,最后,当我循环遍历$all数组并将每个元素的索引作为标题列出索引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')));发布于 2016-02-19 23:36:49
使用嵌套循环:
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()调用修改原始数组。
演示
https://stackoverflow.com/questions/35516778
复制相似问题