Home php Get object fields in php array

Get object fields in php array

Author

Date

Category

There is an array. Each element of the array is an object with two fields.
Example

[{"type": "photo", "photo": {photo}}, {"type": "audio", "audio": {audio}}]

How can I get the object fields from this: type and photo (or audio, no difference)?

$ a [‘type’] doesn’t work


Answer 1

Something like this:

$ obj_array = json_decode ('[{"type": "photo", "photo": {"some" : "content"}}, {"type": "audio", "audio": {"some": "content"}}] ');
print_r ($ obj_array);
$ reult = array ();
  foreach ($ obj_array as $ obj) {
    $ type = $ obj- & gt; type;
    $ reult [$ obj- & gt; type] = $ obj- & gt; $ type;
  }
print_r ($ reult);

Output:

Array
(
  [0] = & gt; stdClass Object
    (
      [type] = & gt; photo
      [photo] = & gt; stdClass Object
        (
          [some] = & gt; content
        )
    )
  [1] = & gt; stdClass Object
    (
      [type] = & gt; audio
       = & gt; stdClass Object
        (
          [some] = & gt; content
        )
    )
)
Array
(
  [photo] = & gt; stdClass Object
    (
      [some] = & gt; content
    )
   = & gt; stdClass Object
    (
      [some] = & gt; content
    )
)

Answer 2

Did you give this line just for demonstration?
In general, object properties are accessed like this:

$ a- & gt; type

Accordingly from an array

$ ar [0] - & gt; type

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions