PHP获取两个对象数组的差异 [英] PHP get difference of two arrays of objects

查看:26
本文介绍了PHP获取两个对象数组的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有 array_diffarray_udiff 用于比较两个数组之间的差异,但是我将如何使用两个对象数组进行比较?

I know there is array_diff and array_udiff for comparing the difference between two arrays, but how would I do it with two arrays of objects?

array(4) {
    [0]=>
        object(stdClass)#32 (9) {
            ["id"]=>
            string(3) "205"
            ["day_id"]=>
            string(2) "12"
        }
}

我的数组是这样的,我有兴趣看看基于 ID 的两个数组的区别.

My arrays are like this one, I am interested to see the difference of two arrays based on IDs.

推荐答案

这正是array_udiff 是为了.编写一个函数,以您希望的方式比较两个对象,然后告诉 array_udiff 使用该函数.像这样:

This is exactly what array_udiff is for. Write a function that compares two objects the way you would like, then tell array_udiff to use that function. Something like this:

function compare_objects($obj_a, $obj_b) {
  return $obj_a->id - $obj_b->id;
}

$diff = array_udiff($first_array, $second_array, 'compare_objects');

或者,如果您使用 PHP >= 5.3,您可以只使用 匿名函数 而不是声明一个函数:

Or, if you're using PHP >= 5.3 you can just use an anonymous function instead of declaring a function:

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return $obj_a->id - $obj_b->id;
  }
);

这篇关于PHP获取两个对象数组的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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