2015-04-23 4 views
-3

Php: Сравнить 2 multidimentinal массивы в PHP У меня есть 02 массивов и я хотел бы сравнить его.сравнить 2 многомерные массивы

$first = array(
      0 => array(
       "id" => 45, 
       "name" => "chicago" 
       ), 
      1 => array(
       "id" => 78, 
       "name" => "LA" 
       ), 
    ); 

    $second = array(
      0 => array(
       "id" => 45, 
       "name" => "chicago" 
       ), 
      1 => array(
       "id" => 78, 
       "name" => "LA" 
       ), 
      2 => array(
       "id" => 95, 
       "name" => "Washington" 
       ), 
    ); 

После сравнить 2 массивы я хотел бы иметь этот

$cityMissing =array (
        0 => array(
        "id" => 95, 
        "name" => "Washington" 
        ); 


**Please, I need your help.** 
+0

Пожалуйста, покажите нам, что вы пробовали первый, поэтому мы может помочь вам исправить это. –

ответ

0

Вы можете использовать array_diff_assoc:

$arrayFirst = array("0" => array("id", "45")); 
$arraySecond = array("0" => array("id", "45"), "1" => array("id", "95")); 

$result = array_diff_assoc($arraySecond, $arrayFirst); 

print_r($result); 

Array 
(
    [1] => Array 
    (
     [0] => id 
     [1] => 95 
    ) 
) 
+0

, что будет комментарий –

+0

это не работает, у меня есть ошибка: Обратите внимание: преобразование массива в строку – Niels

0
public static function array_diff_assoc_recursive($a, $b){ 
     // Get all of the "compare against" arrays 
     $b = array_slice(func_get_args(), 1); 
     // Initial return value 
     $ret = array(); 

     // Loop over the "to" array and compare with the others 
     foreach($a as $key=>$val){ 
      // We should compare type first 
      $aType = gettype($val); 
      // If it's an array, we recurse, otherwise we just compare with "===" 
      $args = $aType === 'array' ? array($val) : true; 

      // Let's see what we have to compare to 
      foreach($b as $x){ 
       // If the key doesn't exist or the type is different, 
       // then it's different, and our work here is done 
       if(!array_key_exists($key, $x) || $aType !== gettype($x[$key])){ 
        $ret[$key] = $val; 
        continue 2; 
       } 

       // If we are working with arrays, then we recurse 
       if($aType === 'array'){ 
        $args[] = $x[$key]; 
       } 
       // Otherwise we just compare 
       else{ 
        $args = $args && $val === $x[$key]; 
       } 
      } 

      // This is where we call ourselves with all of the arrays we got passed 
      if($aType === 'array'){ 
       $comp = call_user_func_array(array(get_called_class(), 'array_diff_assoc_recursive'), $args); 
       // An empty array means we are equal :-) 
       if(count($comp) > 0){ 
        $ret[$key] = $comp; 
       } 
      } 
      // If the values don't match, then we found a difference 
      elseif(!$args){ 
       $ret[$key] = $val; 
      } 
     } 
     return $ret; 
    }