I have an object inside an array stored in the variable $image
array(1) { [250]=> object(MagentoFrameworkDataObject)#11025 (1) { ["_data":protected]=> array(26) { ["value_id"]=> string(3) "250" ["file"]=> string(58) "/i/n/insetktenschutz-doppeltuer-im-zargenrahmen_37_1_3.jpg" ... } } }
If I try to return a value, e.g. file like this:
echo $image->getFile();
Then of course I get Fatal error: Uncaught Error: Call to a member function getFile() on array
So I tried to call it like this:
$image = $image[0];
echo $image->getFile();
But I get Exception #0 (Exception): Notice: Undefined offset: 0
So I tried to cast it to an object:
$image = (object) $image;
echo $image->getFile();
Now I get Fatal error: Uncaught Error: Call to undefined method stdClass::getFile()
Then I used a foreach
:
foreach($image as $i) {
echo $image->getFile(); // alternative: $image->getData('file')
}
and it works! Why does it work with foreach and how can I make it work without?
2
Answers
You can try with reset array function of PHP to get first element of array
I don’t think that there is anything like a functional forEach in php, anyway you could make an ArrayObject subclass in order to encapsulate the iteration logic
EDIT
a more generic version