Question

I have two arrays.

$paternalSiblings = fname => John lname => Doe gender => M birth_year => 1988
                    fname => Sophie lname => Ellison gender => F birth_year => 1990

$maternalSiblings = fname => John lname => Smith gender => M birth_year => 1997    
                    fname => John lname => Doe gender => M birth_year => 1988

Output of the arrays:

Array ( [0] => Array ( [fname] => John [lname] => Doe [birth_year] => 1988[gender] => Male [fname] => Sophie [lname] => Ellison [birth_year] => 1990 [death_date] => [gender] => Female ) ) 
Array ( [0] => Array ( [fname] => John [lname] => Doe [birth_year] => 1988[gender] => Male [fname] => John [lname] => Smith [birth_year] => 1997 [death_date] => [gender] => Male ) ) 

$fullSiblings = $this->arrayIntersect( $paternalSiblings , $maternalSiblings );

<?php
function arrayIntersect( $primary_array, $secondary_array ) {

     if ( !is_array( $primary_array ) || !is_array( $secondary_array ) ) {
         return false;
     }

     if ( !empty( $primary_array ) ) {

         foreach( $primary_array as $key => $value ) {

             if ( !isset( $secondary_array[$key] ) ) {
                 unset( $primary_array[$key] );
             } else {
                 if ( serialize( $secondary_array[$key] ) != serialize( $value ) ) {
                     unset( $primary_array[$key] );
                 }
             }

         }

         return $primary_array;

     } else {
         return array();
     }

     } 
    ?>

This function doesn't work. How could I intersect and differ the arrays? I noticed that built-in functions array_intersect_assoc() and array_diff_assoc() don't work with multidimensional arrays. What's the best way to achieve the goal?

Was it helpful?

Solution

You need at least a fixed value to identify each row, and check differences for others values.

$first = array(
 "uniqueId1" => array("name" => "Ignacio", "email" => "user@server.com"),
 "uniqueId2" => array("name" => "John", "email" => "jh@server.com")
);

$second = array(
 "uniqueId1" => array("name" => "Ignacio", "email" => "other@server.com"),
 "uniqueId2" => array("name" => "Luis", "email" => "jh@server.com")
);

And you cand compare and get differences with:

foreach($first as $keyRow => $firstRow) {
 if(isset($second[$keyRow])) { //The first row exists in second array, so, I will check it
  foreach($firstRow as $key => $value) {
   if($second[$keyRow][$key] != $value) {
    echo "For row: ".$keyRow.", ".$second[$keyRow][$key]." is not equal to: ".$value."<br />";
   }
  }
 }
}

Output:

For row: uniqueId1, other@server.com is't equal to: user@server.com
For row: uniqueId2, Luis is't equal to: John
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top