PHP - 搜索对象数组

3

我有一个来自Volume类的对象数组。我正在寻找最好的方法,通过给定的_id值(访问器方法是get_description),返回_description属性。

在下面的例子中,我会提供"vol-e123456a3",它会返回"server E: volume"。

 [0] => Volume Object
        (
            [_snapshot_count:protected] => 16
            [_id:protected] => vol-e123456a3
            [_description:protected] => server E: volume
            [_region:protected] => us-east-1
            [_date_created:protected] => DateTime Object
                (
                    [date] => 2013-04-06 10:29:41
                    [timezone_type] => 2
                    [timezone] => Z
                )

            [_size:protected] => 100
            [_state:protected] => in-use
        )

“最好的方式”是什么意思?你在尝试什么吗? - Rohan Kumar
2
请看这篇帖子:https://dev59.com/bG445IYBdhLWcg3wq8Pp - Robbert
2个回答

0

试试这个,

$_id="vol-e123456a3";
foreach($objArray as $obj)
{
    if($obj->_id==$_id)
    {
       return isset($obj->_description) ? $obj->_description : "";
    }
}

0
你可以使用以下函数;数据成员被标记为受保护的,所以为了从公共方面访问它们,你需要使用访问器方法,但是你没有指定。我已经猜测了最常见的访问器名称。
function getValue($object_array, $filter) {
    foreach ($object_array as $object) 
       if ($object->getId() == $filter) return $object->getDescription();
    return false;
}

使用以下参数调用它

$description = getValue($objects, 'vol-e123456a3');

如果没有公共访问器方法,我们将需要使用反射。如下所示。
function getValue($object_array, $filter) {
    foreach ($object_array as $object)  {
        $class = new ReflectionClass($object);
        $prop = $class->getProperty('_id')->getValue($object);
       if ($prop == $filter) return $class->getProperty('_description')->getValue($object)
    }
    return false;
}

我不需要查找任何 getId()getDescription() - Rohan Kumar
您已经指定了,但是您也应该指定“方法名称”。 - Rohan Kumar
@RohanKumar 我已经更新了我的答案,使其更加完整。 - DevZer0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接