-2

I am attempting to iterate the img data held in the array within the stdClass object. I've been able to get the stdClass to do everything else I hoped, trying to get the images to sequence/iterate out has eluded me. I have looked at php.net and read through stack for an answer i can understand which explains the error I have in addition to having unsuccessfully to google the answer. I am now very confused and tried many many things will no successes.

$myObj = new stdClass;
$myObj->image=['x01.jpg', 'x02.jpg', 'x03.jpg', 'x04.jpg', 'x05.jpg'];
$myObj->name="asdfg";
$myObj->phone="exaasdfaspg";
$myObj->email="exsdfg";

$myObjArray[] = $myObj;

foreach($myObjArray as $myObj)
{ echo '<img src="_imgResevior/' . $myObj->image[] . '"/>' ;}
#{ echo (in_array('<img src="_imgResevior/' . $myObj->image['image'] . '"/>')) ;}
Chezshire
  • 673
  • 5
  • 12
  • 29
  • 1
    `$myObj->image[]` is not valid unless you are appending to the array i.e. `$myObj->image[] = 'newfile.jpg';`. Use `$myObj->image[0]` or whatever element you're trying to access. Or `foreach ($myObj->image as $image) { ... }` within your first `foreach`. Note that your re-use of variable names (`$myObj`) can also cause unpredictable results if you expect to use the `$myObj` that you originally declared after the `foreach`. – sjagr Jan 15 '15 at 16:24
  • 1
    try `foreach($myObj->image as $myObjArray )` – Robert Jan 15 '15 at 16:26
  • The question is not clear, please specify what is unclear in terms of iterating over an array? – Plamen Nikolov Jan 15 '15 at 16:31
  • @sjagr it's correct the error with `foreach` i think you down vote the answers – Robert Jan 15 '15 at 16:37

2 Answers2

1
foreach($myObjArray as $myObj)
{ echo '<img src="_imgResevior/' . $myObj->image[] . '"/>' ;}

should be

foreach($myObj->image as $myObjArray )
{ echo '<img src="_imgResevior/' . $myObjArray . '"/>' ;}

the output html code is

<img src="_imgResevior/x01.jpg">
<img src="_imgResevior/x02.jpg">
<img src="_imgResevior/x03.jpg">
<img src="_imgResevior/x04.jpg">
<img src="_imgResevior/x05.jpg">
Robert
  • 1,890
  • 2
  • 23
  • 32
0

You cannot access an object as array. If you want this you need to implement the ArrayAccess Interface.

To get your code working just change the foreach to this:

foreach($myObj->image as $img)
{ 
  echo '<img src="_imgResevior/' . $img . '"/>';
}
Plamen Nikolov
  • 1,910
  • 1
  • 11
  • 19
  • 1
    Thank you, this worked. Also thank you for pointing me too the ArrayAccess Interface which I will read during my lunch at school; The second answer also works. Thanks for the help, it is greatly appreciated. – Chezshire Jan 15 '15 at 16:35