Moving object properties with dynamic names

I am trying to get current trends from twitter api (but this is not relevant).

I get information as an object. In this situation, some of the properties that I need to access relate to the dates since the last update of the trends, so I can not hard-code the property names.

Here is an example: I did not explain myself very well, which, I am afraid, did not: (

stdClass Object ( [2011-03-09 02:45] => Array ( [0] => stdClass Object ( [promoted_content] => [events] => [query] => RIP Mike Starr [name] => RIP Mike Starr ) [1] => stdClass Object ( [promoted_content] => [events] => [query] => Mac & Cheese [name] => Mac & Cheese ) 

Note. This is not a complete object.

+4
source share
2 answers

You can traverse the properties of an object using get_object_vars()

 $fooBar = new stdClass(); $fooBar->apple = 'red'; $fooBar->pear = 'green'; foreach(get_object_vars($fooBar) as $property => $value) { echo $property . " = " . $value . "\n"; } // Output // apple = red // pear = green 
+10
source

Do you get this data as JSON? If so, check out the second json_decode argument , which allows you to get the results back as an associative array, not as an object. This will allow you to use the usual loop constructs like foreach and get the keys using array_keys .

If you do not receive this data through JSON, you can use Reflection to capture the properties of the object . (edit # 2: I'm not sure if this will work on stdClass or not, actually ...)

+4
source

Source: https://habr.com/ru/post/1343101/


All Articles