php::array_diff() 到非标量,比如对象

php::array_diff() to non-scalar, like objects

我需要得到两个对象数组之间的差异,但是 array_diff() 比较数组元素,如 (string) $value1 === (string) $value2,它会导致转换失败,如 Warning: Uncaught Object of class YourClass could not be converted to string

基本上我有两个数组,比如:

<?php

// Simulating objects:
$value1 = (object) [ "value" => 1 ];
$value2 = (object) [ "value" => 2 ];
$value3 = (object) [ "value" => 3 ];

// Arrays:
$array1 = [ $value1, $value2 ];
$array2 = [ $value2, $value3 ];

// Difference:
$arrayDifference = array_diff($array1, $array2);

// Expected:
$arrayDifference = [ $array1 ];

// What happen:
// Warning: Uncaught Object of class stdClass could not be converted to string

我只需要检查是否 $object1 == $object2

尝试关注

   <?php

    function array_difference($array1,$array2){
         $result=array();
         foreach($array1 as $a1){
             if(!in_array($a1,$array2)){
                 array_push($result,$a1);
             }
         }
         return $result;
     }
    // Simulating objects:
    $value1 = (object) [ "value" => 1 ];
    $value2 = (object) [ "value" => 2 ];
    $value3 = (object) [ "value" => 3 ];

    // Arrays:
    $array1 = [ $value1, $value2 ];
    $array2 = [ $value2, $value3 ];

    $arrayDifference=array_difference($array1,$array2);
    var_dump($arrayDifference);

输出将是

array (size=1)
  0 => 
    object(stdClass)[1]
      public 'value' => int 1