Home >Backend Development >PHP Tutorial >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', ), )
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!