有效的方式通过属性来搜索对象的数组 [英] efficient way to search object in an array by a property

查看:108
本文介绍了有效的方式通过属性来搜索对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,有这样的:

$array[0]->id = 'one';
$array[0]->color = 'white';
$array[1]->id = 'two';
$array[1]->color = 'red';
$array[2]->id = 'three';
$array[2]->color = 'blue';

这将是实现像

功能findObjectById($ ID){}

function findObjectById($id){}

这将返回对象数组$ [0]如果我叫:

that would return the object $array[0] if i called:

$obj = findObjectById('one')

如果我通过'四'作为一个参数将返回false。

and would return false if i passed 'four' as a param.

推荐答案

您可以遍历的对象:

function findObjectById($id){
    $array = array( /* your array of objects */ );

    foreach ( $array as $element ) {
        if ( $id == $element->id ) {
            return $element;
        }
    }

    return false;
}

编辑:

更快的方式是有一个与钥匙等于对象的ID的数组(如果唯一的);

Faster way is to have an array with keys equals to objects' ids (if unique);

然后你就可以建立你的功能如下:

Then you can build your function as follow:

function findObjectById($id){
    $array = array( /* your array of objects with ids as keys */ );

    if ( isset( $array[$id] ) ) {
        return $array[$id];
    }

    return false;
}

这篇关于有效的方式通过属性来搜索对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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