检查数组中是否存在对象 [英] Check if an object exists in an array

查看:87
本文介绍了检查数组中是否存在对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个人对象的数组,这个对象看起来像这样:

I've got an array with multiple person-objects in it, this objects look like this:

id: 1,
name: 'Max Muster',
email: 'max.muster@example.com',
language: 'German'

现在,我将对象放在另一个数组中,看起来并不完全相同:

Now, I've got objects in another array, which doesn't look exactly the same:

id: 1,
name: 'Max Muster',
email: 'max.muster@example.com',
language: 'de'

我有一个foreach循环来遍历数组2并检查对象是否存在于数组中1。

I've got a foreach-loop to loop through array 2 and check if the objects exists in array 1.

foreach($array2 as $entry) {
    if(existsInArray($entry, $array1)) {
        // exists
    } else {
        // doesn't exist
    }
}

如果我的对象存在于数组中,是否有一个函数要检查(例如我的existInArray())?我只需要检查对象ID是否存在,其他属性就没有关系。

Is there a function to check (like my existsInArray()), if my object exists in the array? I just need to check, if the object-id exists, other attributes doesn't matter.

推荐答案

将对象ID用作将对象放入数组时的键:

Use the object IDs as keys when you put the objects in the array:

$array1[$object->id] = $object;

然后使用 isset($ array1 [$ object-&id; id]) 检查对象是否已存在于 $ array

then use isset($array1[$object->id]) to check if the object already exists in $array:

if (isset($array1[$object->id])) {
    // object exists in array; do something
} else {
    // object does not exist in array; do something else
}

这篇关于检查数组中是否存在对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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