PHP-从对象数组中按对象属性查找条目 [英] PHP - find entry by object property from an array of objects

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

问题描述

该数组如下:

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

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

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

And I have a integer variable called $v.

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

How could I select an array entry that has a 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

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

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