【问题标题】:PHP - Searching an array of objects [duplicate]PHP - 搜索对象数组[重复]
【发布时间】:2013-09-08 18:46:03
【问题描述】:

我有一个 Volume 类的对象数组。我正在寻找在给定 _id 值的情况下返回 _description 属性的最佳方式(访问器方法是 get_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
        )

【问题讨论】:

标签: php oop


【解决方案1】:

试试这个,

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

【讨论】:

    【解决方案2】:

    您可以使用以下功能;数据成员被标记为受保护,因此为了从公共端访问它们,您将不得不使用您未指定的访问器方法。我已经用最常见的可能访问者名称进行了猜测。

    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()
    • 你已经指定了,但你也应该指定name of methods
    • @RohanKumar 我已经更新了我的答案以更完整
    猜你喜欢
    • 2018-03-25
    • 2015-05-18
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多