[英]Compare two multidimensional arrays and unset matched elements
更新:得到答復后,我意識到我應該嘗試使用數據庫查詢解決此問題,所以我在這里寫了更詳細的文章
原始帖子:我想比較兩個多維數組,並刪除符合特定條件的元素。 我知道我將不得不使用一些鍵在數組中循環,然后取消設置,但是我似乎無法正確地做到這一點。
這兩個數組是$all
,用於存儲所有可用的房間及其床,而$reserved
則僅用於保留所有房間和所有床。
我想遍歷所有預訂並獲取位於$reservations[x][0]
位置的房間標題,其中x是當前查看的預訂,並將其與$all[a][0]
中的所有元素進行比較,其中a是當前查看的房間。
因此,當我發現$all[0][0]
=>'Luxury Room'的值與$reservations[0][0]
=>'Luxury Room'的值匹配時,我將查看床位和床位代碼y,其中y是當前查看的床位代碼$reservations[x][1][y]
,並將其與匹配房間的所有可用床位進行比較,從而與$all[0][1][b]
,其中b都可用房間。
當我發現$all[0][1][1]
=>'xx2'的值與$reservations[0][1][0]
=>'xx2'中的值匹配時,我將取消設置索引0 1從$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')));
使用嵌套循環:
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()
調用可修改原始數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.