douxunnian0423 2011-02-13 13:23
浏览 37
已采纳

PHP foreach循环破坏子对象

I'm trying to access third party api which gives me object and sub object, for example:

stdClass 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

  • 写回答

3条回答 默认 最新

  • duan0818 2011-02-13 14:09
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)