Home > Backend Development > PHP Tutorial > How to Find Rows Present in One Multidimensional Array but Not in Another?

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

Susan Sarandon
Release: 2024-11-09 09:39:02
Original
871 people have browsed it

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

Comparing Associative Rows of Multidimensional Arrays

You have two multidimensional arrays, $pageids and $parentpage, where each row represents a record with columns 'id', 'linklabel', and 'url'. You want to find the rows present in $pageids but not in $parentpage, effectively creating an array ($pageWithNoChildren) with the missing rows.

However, using array_diff_assoc() directly on these arrays will not work as expected because it compares the primary array keys, not the content of the nested rows. To compare the nested rows, we can first convert them to one-dimensional arrays using array_map() and the serialize() function.

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

After converting them, we can use array_diff() to compare these one-dimensional arrays and obtain the difference.

$serializedDifference = array_diff($serializedPageids, $serializedParentpage);
Copy after login

Finally, we can convert the serialized difference back into multidimensional arrays using array_map() and the unserialize() function.

$pageWithNoChildren = array_map('unserialize', $serializedDifference);
Copy after login

This process allows us to compare the content of the nested rows and extract the rows that are present in $pageids but not in $parentpage, resulting in the expected output:

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',
  ),
)
Copy after login

The above is the detailed content of How to Find Rows Present in One Multidimensional Array but Not in Another?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template