PHP foreach循环破坏子对象

时间:2011-02-13 13:23:33

标签: php object foreach

我正在尝试访问第三方api,它为我提供了对象和子对象,例如:

stdClass Object
(
    [truncated] => 
    [text] => "some text"
    [user] => stdClass Object
        (
            [count] => 9370
            [comments_enabled] => yes

当我尝试使用以下代码遍历对象时,我在子对象'us​​er'的开头遇到错误。任何人都可以帮助我1)迭代子对象,或2)阻止循环中的子对象。

代码:

$test = $s[0];
$obj = new ArrayObject($test);
foreach ($obj as $data => $name) {
print $data . ' - ' . $name . '<br />';
}

感谢

3 个答案:

答案 0 :(得分:0)

<?php

function traceObject($object) {
  foreach ($object as $data => $name) {
    if (is_object($name)) {
      traceObject($name);
    } else {
      echo $data . ' - ' . $name .'<br />';
    }
  }
}

答案 1 :(得分:0)

这将迭代一个对象树并打印键 - 值对...

printObject($test);

function printObject($obj) {
    foreach (get_object_vars($obj) as $field => $value) {
        if (is_object($value)) {
            printObject($value);
        } else {
            print $field . ' - ' . $value . '<br />';
        }
    }
}

答案 2 :(得分:0)

这是因为'user'字段是一个对象,所以你需要单独遍历该对象中的每个字段

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 );

将输出

truncated - 
text - some text
user.count - 9370
user.comments_enabled - yes