1

I have an object like this:

    myObj = {"id":12,"title":"my title","content":"my content"}

I want to loop through all the element of this object to have something like this:

    echo " $key ." = ". $value

    result : id = 12
             title = my title
             content = my content

but if I loop through my object like this:

foreach ($obj as $key => $value) {
       echo "$key = $value\n";
 }

and I got this result :

incrementing => 1
exists => 1
wasRecentlyCreated => 

How can I get the elements of my object?

hunch_hunch
  • 2,283
  • 1
  • 21
  • 26
Yassin
  • 21
  • 1
  • 6
  • you could use `get_object_vars()` then loop through the resulting array with `$someLoopedValFromArr = $object->{$someLoopedValFromArr}`, – Derek Pollard May 30 '18 at 20:39
  • 1
    Confused by question... you got results that are not at all present in `myObj`? Or is this just a bad example of your issue? – ficuscr May 30 '18 at 20:41

1 Answers1

2

Check this code:

$myObj = '{"id":12,"title":"my title","content":"my content"}';

$object = json_decode($myObj);

foreach($object as $key => $value) {
  echo $key . " = " . $value . "<br>";
};

More information

Try it online

Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39