首頁 >後端開發 >php教程 >如何找到一個多維數組中存在但另一個多維數組中不存在的行?

如何找到一個多維數組中存在但另一個多維數組中不存在的行?

Susan Sarandon
Susan Sarandon原創
2024-11-09 09:39:02884瀏覽

How to Find Rows Present in One Multidimensional Array but Not in Another?

比較多維數組的關聯行

您有兩個多維數組,$pageids 和$parentpage,其中每行代表一個包含列的記錄“id”、“連結標籤”和“url”。您想要尋找 $pageids 中存在但 $parentpage 中不存在的行,從而有效地建立一個包含缺少行的陣列 ($pageWithNoChildren)。

但是,直接在這些數組上使用 array_diff_assoc() 將無法按預期工作因為它比較主數組鍵,而不是嵌套行的內容。要比較巢狀行,我們可以先使用 array_map() 和 serialize() 函數將它們轉換為一維陣列。

$serializedPageids = array_map('serialize', $pageids);
$serializedParentpage = array_map('serialize', $parentpage);

轉換它們之後,我們可以使用 array_diff() 來比較這些行維數組並獲得差值。

$serializedDifference = array_diff($serializedPageids, $serializedParentpage);

最後,我們可以用 array_map() 將序列化差值轉換回多維數組, unserialize() 函數。

$pageWithNoChildren = array_map('unserialize', $serializedDifference);

此過程可讓我們比較巢狀行的內容並擷取 $pageids 中存在但 $parentpage 中不存在的行,從而產生預期的輸出:

array (
  0 =>
  array (
    'id' => 1,
    'linklabel' => 'Home',
    'url' => 'home',
  ),
  3 =>
  array (
    'id' => 6,
    'linklabel' => 'Logo Design',
    'url' => 'logodesign',
  ),
  4 =>
  array (
    'id' => 15,
    'linklabel' => 'Content Writing',
    'url' => 'contentwriting',
  ),
)

以上是如何找到一個多維數組中存在但另一個多維數組中不存在的行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn