如何从对象数组中按对象属性查找条目? [英] How to find entry by object property from an array of objects?

查看:29
本文介绍了如何从对象数组中按对象属性查找条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组看起来像:

[0] => stdClass Object
        (
            [ID] => 420
            [name] => Mary
         )

[1] => stdClass Object
        (
            [ID] => 10957
            [name] => Blah
         )
...

我有一个名为 $v 的整数变量.

And I have an integer variable called $v.

如何选择具有 ID 属性具有 $v 值的对象的数组条目?

How could I select an array entry that has an object where the ID property has the $v value?

推荐答案

您可以迭代数组,搜索特定记录(仅在一次搜索中就可以)或使用另一个关联数组构建哈希图.

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

对于前者,像这样

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

有关后者的更多信息,请参阅此问题和后续答案 - 参考 PHP 数组多个索引

See this question and subsequent answers for more information on the latter - Reference PHP array by multiple indexes

这篇关于如何从对象数组中按对象属性查找条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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