Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse an object's properties with dynamic names

I am trying to get the current trends from the twitter api (but that's sorta irrelevant).

I receive the information as an object. In this situation some of the properties that I need to access, are dates from when the trends were last updated, therefore I can't hard code the property names.

Here's an example incase I didn't explain myself well, which I fear I didn't :(

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 the full object

like image 778
Paramount Avatar asked Mar 10 '11 02:03

Paramount


People also ask

How do you access object properties dynamically?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .


2 Answers

You can traverse an object's properties 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
like image 177
Mike B Avatar answered Sep 29 '22 16:09

Mike B


Are you getting this data as JSON? If so, check out the second argument to json_decode, which lets you get the results back as an associative array instead of as an object. This will let you use the normal loop constructs, like foreach and obtain keys using array_keys.

If you aren't getting this data via JSON, you can consider using Reflection to grab the properties of an object. (edit #2: I'm not sure if this will work on stdClass or not, actually...)

like image 21
Charles Avatar answered Sep 29 '22 17:09

Charles