【问题标题】:PHP compare two objects with same properties but different properties values, get non-matching valuesPHP比较两个具有相同属性但属性值不同的对象,得到不匹配的值
【发布时间】:2013-05-13 18:10:35
【问题描述】:

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

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

代码背后的故事是,当每个人到达时,我打开一个文件,在某个时间点,我希望每个人在他的姓名和身份下方列出他的姓名和身份(每次到达时都相同) ) 以连续列出他的到达文件。

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

【问题讨论】:

  • 在您未经测试并在生产时启动它之前,没有代码是糟糕的代码。让我们看看你有什么。

标签: php object comparison


【解决方案1】:

为此有内置函数。您确实需要将对象转换为数组才能使其正常工作(这是对象的所有公共属性的数组)。假设你的变量被称为$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);

【讨论】:

  • 这正是我想要的。谢谢分配。你拯救了我的一天
  • 不幸的是,这不适用于不可转换为字符串的属性。
  • @Florian 确实不会,很好。在这些情况下,您必须使比较更加精细,并为那些无法手动转换的变量创建一个字符串,或者以某种方式手动比较字段。
  • 是的,我找到的唯一解决方案是一个很好的旧循环和身份比较,收集那些不同的人:/
  • 简称(array) $classA == (array) $classB
猜你喜欢
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
相关资源
最近更新 更多