3

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
        )
2
  • What do you mean by the best way, Are you trying something? Commented Sep 5, 2013 at 4:31
  • 2
    Take a look at this posting: stackoverflow.com/questions/4742903/… Commented Sep 5, 2013 at 4:31

2 Answers 2

0

Try this,

$_id="vol-e123456a3";
foreach($objArray as $obj)
{
    if($obj->_id==$_id)
    {
       return isset($obj->_description) ? $obj->_description : "";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

I'm not looking any getId() and getDescription().
You have specified but you should specify the name of methods too
@RohanKumar i've updated my answer to be more complete

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.