How to Find Dissimilar Nested Arrays within Multidimensional Arrays?

Susan Sarandon
Release: 2024-11-16 14:19:03
Original
829 people have browsed it

How to Find Dissimilar Nested Arrays within Multidimensional Arrays?

Find Dissimilar Nested Arrays in Multidimensional Arrays

Consider the following two arrays containing associative rows of information:

$pageids = [
    ['id' => 1, 'linklabel' => 'Home', 'url' => 'home'],
    ['id' => 2, 'linklabel' => 'Graphic Design', 'url' => 'graphicdesign'],
    ['id' => 3, 'linklabel' => 'Other Design', 'url' => 'otherdesign'],
    ['id' => 6, 'linklabel' => 'Logo Design', 'url' => 'logodesign'],
    ['id' => 15, 'linklabel' => 'Content Writing', 'url' => 'contentwriting'],
];

$parentpage = [
    ['id' => 2, 'linklabel' => 'Graphic Design', 'url' => 'graphicdesign'],
    ['id' => 3, 'linklabel' => 'Other Design', 'url' => 'otherdesign'],
];
Copy after login

Our task is to identify and return the associative rows present in $pageids but absent in $parentpage. However, using array_diff_assoc() on the first level of these arrays doesn't provide the desired result.

To overcome this challenge, we can leverage a combination of array_map() and serialize() functions. This approach converts each sub-array into a string representation, effectively flattening the multidimensional structure.

$pageWithNoChildren = array_map('unserialize',
    array_diff(array_map('serialize', $pageids), array_map('serialize', $parentpage)));
Copy after login
  1. array_map('serialize', $pageids): Converts each sub-array in $pageids into a string representing its structure.
  2. array_map('serialize', $parentpage): Same process for $parentpage.
  3. array_diff(): Compares the string representations and returns an array of differences.
  4. array_map('unserialize', ...): Converts the string differences back into sub-arrays to restore the desired structure.

The resulting $pageWithNoChildren array contains the sub-arrays from $pageids that are not present in $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',
  ),
)
Copy after login

The above is the detailed content of How to Find Dissimilar Nested Arrays within Multidimensional Arrays?. 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