我需要在两个对象数组之间获得差异,但是array_diff()
比较像template<typename Functor, typename ... Args>
auto wrapper(Functor &&f, Args &&... args) -> decltype(f(std::forward<Args>(args)...)){
return f(std::forward<Args>(args)...);
}
这样的数组元素,它会导致转换失败,如(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
。
答案 0 :(得分:1)
尝试以下
<?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