PHP比较两个属性相同但属性值不同的对象,得到不匹配的值


PHP compare two objects with same properties but different properties values, get non-matching values

我有两个对象包含在一个数组中:

array (size=2)
 0 => 
object(stdClass)[20]
  public 'name' => string 'John' (length=4)
  public 'surname' => string 'D' (length=1)
  public 'id_number' => string '924' (length=3)
  public 'file' => string '1001' (length=4)
  public 'arrival_date' => string '1368466111' (length=10)
1 => 
object(stdClass)[21]
  public 'name' => string 'John' (length=4)
  public 'surname' => string 'D' (length=1)
  public 'id_number' => string '924' (length=3)
  public 'file' => string '1002' (length=4)
  public 'arrival_date' => string '1368466190' (length=10)

如果能像下面这样有3个数组或3个对象就好了:

array('name'=>'John','surname'=>'D','id_number'=>'924') - contains the matching values
array('file'=>'1001','arrival_date'=>'1368466111') - contains the first set of different values
array('file'=>'1002','arrival_date'=>'1368466190') - 2nd set of not matching values

代码背后的故事是,在每个人到达时,我打开一个文件,在某个时间点,我希望每个人列出他的名字,并在他的名字和身份证明(每次到达时都是相同的)下面列出他的到达文件,每一行。

你觉得呢?有什么简单的方法可以做到这一点吗?到目前为止,我所做的是一团糟——大量的代码和糟糕的结果。

有内置的函数。您确实需要将对象强制转换为数组才能工作(这是对象的所有公共属性的数组)。假设变量名为$var:

$a1 = (array)$var[0];
$a2 = (array)$var[1];
$inBoth       = array_intersect_assoc($a1, $a2);
$onlyInFirst  = array_diff_assoc($a1, $a2);
$onlyInSecond = array_diff_assoc($a2, $a1);