php访问对象值

时间:2012-09-27 23:19:49

标签: php object foreach

stdClass Object
(
    [request] => stdClass Object
        (
            [other] => stdClass Object
                (
                    [4] => stdClass Object
                        (
                            [answer] => one
                        )

                    [5] => stdClass Object
                        (
                            [answer] => two
                        )

                    [6] => stdClass Object
                        (
                            [answer] => three
                        )
                )

        )
)
?>

我可以通过与foreach循环打印出所有答案。

foreach( $result->request->other as $test )
      $tests[] = $test->answer;
            foreach($tests as $test1){
            echo "<p>$test1</p><br>";
          }

我对如何回应答案编号感到有点困惑,在这种情况下是4 5 6.我如何回应它们作为循环的一部分。例如:

4 one
5 two
6 three

2 个答案:

答案 0 :(得分:1)

foreach( $result->request->other as $key => $test )
      $tests[] = $test->answer;
            foreach($tests as $test1){
            echo "<p>$test1</p><br>";
          }

只需更改foreach行即可包含$ key =&gt;在$ test变量之前。这将是索引(数字或关联),您可以获得该值,并随意使用它。

答案 1 :(得分:1)

使用foreach( $array AS $key=>$val )语法,如下所示:

foreach( $result->request->other as $key=>$test ) {
  printf( "<p>%s: %s</p><br />", $key, $test->answer );
}