"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-17
Browse:320

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);

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

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

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

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

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',
  ),
)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3