如何交叉和区分多维数组

时间:2013-12-15 17:59:55

标签: php arrays multidimensional-array intersect

我有两个数组。

$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

数组的输出:

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

     } 
    ?>

此功能不起作用。我怎么可以交叉和区分数组?我注意到内置函数array_intersect_assoc()和array_diff_assoc()不适用于多维数组。实现目标的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

您至少需要固定值来标识每一行,并检查其他值的差异。

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

你可以比较并得到差异:

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 />";
   }
  }
 }
}

输出:

For row: uniqueId1, other@server.com is't equal to: user@server.com
For row: uniqueId2, Luis is't equal to: John