0

I have this array of std class object:

$myarray = 
    Array
    (
        [0] => stdClass Object
            (
                [text] => lorem lorem
                [src] => web
            )

        [1] => stdClass Object
            (
                [text] => ipsum ipsum
                [src] => book
            )
    )

and I have a $value = "lorem lorem", that I want to look up in the array and return the src of that object.

here is my attempt:

foreach($myarray -> 'text' as $key => $text_value){
    if($value == $text_value){
          $new_src = $myarray -> 'src';
    }
}
1
  • $myarray -> 'text' ?? Commented Jun 14, 2017 at 10:42

3 Answers 3

1

You're almost there, you need to loop through the array and then check the object's text attribute:

foreach ($myarray as $object) {
    if ($object->text == $text_value){
          $new_src = $object->src;
    }
}

This will iterate the array items and grab each StdClass object, you can then use that object to compare text against $text_value and update the $new_src if it matches.

Sign up to request clarification or add additional context in comments.

Comments

1

You can filter the by $item->text == $value

$value = "lorem lorem"
$array = array_filter($myarray, function($v) use($value) {
  return $v->text == $value;
});
$srcs = array_map(function($v){return $v->src;}, $array);
print_r($srcs);

Comments

0

I think this will helpful, I have slightly changed the #1 answer

$src = getSrc($myarray, $value);

function getSrc($objArray, $text) {
    foreach($objArray as $obj){
        if ($obj->text == $value)
            return $obj->src;
    }
    return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.