PHP - 搜索对象数组[重复]

This question already has an answer here:

I have an array of objects from class Volume. I am looking for the best way to return the _description property given an _id value (accessor method is get_description).

In the below example, I would provide "vol-e123456a3" and it would return "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
        )
</div>

Try this,

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

you can use the following function; the data members are marked protected so in order to access them from public side you will have to use accesor methods, which you have not specified. i have placed a guess with the most common possible accesor name.

function getValue($object_array, $filter) {
    foreach ($object_array as $object) 
       if ($object->getId() == $filter) return $object->getDescription();
    return false;
}

call it with the following params

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

if there are no public accessor methods we will need to use reflection. as follows

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;
}