PHP foreach loop breaking with sub object
I'm trying to access third party api which gives me object and sub object, for example:
stdClass 开发者_StackOverflow中文版Object
(
[truncated] =>
[text] => "some text"
[user] => stdClass Object
(
[count] => 9370
[comments_enabled] => yes
When I try and loop through the object with the following code I get an error at the start of sub-object 'user'. Can anyone help me either 1) iterate through the sub-object, or 2) block the sub-object from the loop.
The code:
$test = $s[0];
$obj = new ArrayObject($test);
foreach ($obj as $data => $name) {
print $data . ' - ' . $name . '<br />';
}
thanks
It's because the 'user' field is an object, so you need to separately run through each field within that object
function iterateObject($obj, $name='') {
//for each element
foreach ($obj as $key=>$val) {
$myName = ($name !='') ? "$name.$key" : $key;
//if type of the element is an object or array
if ( is_object($val) || is_array($val) ) {
//if so, iterate through its properties
iterateObject($val, $myName);
}
//otherwise output name/ value combination
else {
print "$myName - $val <br/>";
}
}
}
$test = $s[0];
$obj = new ArrayObject( $test );
iterateObject( $obj );
Will output
truncated -
text - some text
user.count - 9370
user.comments_enabled - yes
This will iterate through a tree of objects and print key - value pairs...
printObject($test);
function printObject($obj) {
foreach (get_object_vars($obj) as $field => $value) {
if (is_object($value)) {
printObject($value);
} else {
print $field . ' - ' . $value . '<br />';
}
}
}
<?php
function traceObject($object) {
foreach ($object as $data => $name) {
if (is_object($name)) {
traceObject($name);
} else {
echo $data . ' - ' . $name .'<br />';
}
}
}
精彩评论