如何使用in_array php函数搜索std对象数组(对象数组)? [英] How to search in array of std object (array of object) using in_array php function?

查看:147
本文介绍了如何使用in_array php函数搜索std对象数组(对象数组)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下std对象数组

I have following std Object array

Array
(
    [0] => stdClass Object
        (
            [id] => 545
        )

    [1] => stdClass Object
        (
            [id] => 548
        )

    [2] => stdClass Object
        (
            [id] => 550
        )

    [3] => stdClass Object
        (
            [id] => 552
        )

    [4] => stdClass Object
        (
            [id] => 554
        )

)

我想使用循环搜索[id]键的值.我有以下条件来检查值是否存在,如下所示:

I want to search for value of [id] key using loop. I have following condition to check whether value is exist or not like below

$flag = 1;
if(!in_array($value->id, ???)) {
    $flag = 0;
}

???我要在哪里搜索std Object的[id]键的数组.

Where ??? I want to search in array of std Object's [id] key.

有人可以帮我吗?

推荐答案

如果数组不太大或需要多次执行测试,则可以在数组中映射属性:

If the array isn't too big or the test needs to be performed multiple times, you can map the properties in your array:

$ids = array_map(function($item) {
    return $item->id;
}, $array);

然后:

if (!in_array($value->id, $ids)) { ... }

这篇关于如何使用in_array php函数搜索std对象数组(对象数组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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