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
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] .
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
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With