skip to Main Content

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


  1. You can try with reset array function of PHP to get first element of array

    $imageData = reset($image);
    echo $imageData->getData("file");
    
    Login or Signup to reply.
  2. 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

    class MyArray extends ArrayObject {
        public function getData($data){
            foreach($this as $element) {
                $element->getData($data);
            }
        }
    }
    
    // and use it
    $my = new MyArray(array( /* put your objects here */ ));
    $my->getData("file");
    

    EDIT

    a more generic version

    class MyArray extends ArrayObject {
        public function __call($name, $data){
            foreach($this as $element) {
                $element->$name(...$data);
            }
        }
    }
    $my = new MyArray(array( /* put your objects here */ ));
    $my->getData("file");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search