PHP比较具有相同属性但属性值不同的两个对象,获得不匹配的值 [英] PHP compare two objects with same properties but different properties values, get non-matching values

查看:143
本文介绍了PHP比较具有相同属性但属性值不同的两个对象,获得不匹配的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数组中包含了这两个对象:

I have these two objects contained in a array:

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个数组会很棒对象,如下所示:

It would be great to come up with 3 arrays or 3 objects like the following:

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

代码背后的故事是,每个人到来后,我打开一个文件,并且在某个时间点上,我希望每个人都列出他的名字并在他的名字下面和标识(每次到达都相同)以连续列出他的到达文件。

The story behind the code is that upon the arrival of each person, I open a file, and at some point in time, I want each person to list his name and beneath his name and identification (that are identical for each arrival) to list his arrival files, each in a row.

您怎么看?有什么整洁的方法可以做到这一点吗?到目前为止,我所做的只是一团糟-大量的代码,效果不佳。

What do you, think? Is there any neat way to accomplish this? What I did so far is a mess - tons of code with poor results.

推荐答案

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

There are built in functions for that. You do need to cast the objects to an array for this to work though (which is an array of all public properties of the object). Assuming your variable is called $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);

这篇关于PHP比较具有相同属性但属性值不同的两个对象,获得不匹配的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆