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 object fields from this: type and photo (or audio, no difference)?

$ a ['type'] fails

    2 answers 2

    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->type; $reult[$obj->type] = $obj->$type; } print_r($reult); 

    Conclusion:

     Array ( [0] => stdClass Object ( [type] => photo [photo] => stdClass Object ( [some] => content ) ) [1] => stdClass Object ( [type] => audio [audio] => stdClass Object ( [some] => content ) ) ) Array ( [photo] => stdClass Object ( [some] => content ) [audio] => stdClass Object ( [some] => content ) ) 

      Did you bring the string just for demonstration? In general, the properties of an object are addressed as follows:

       $a->type 

      Respectively from the array

       $ar[0]->type 
      • If the string is not for demonstration, but in this form (as a string) you get an array from where either. First you need to use json_decode - Vorobyev Alexander