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

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

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

        )
)
?>

I'm able to print out all the answers by looping with a foreach.

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

I'm a little confused on how to also echo out the answer number which in this case is 4 5 6. How do i echo them out as part of the loop. ex:

4 one
5 two
6 three

2 Answers 2

1

use foreach( $array AS $key=>$val ) syntax, like this:

foreach( $result->request->other as $key=>$test ) {
  printf( "<p>%s: %s</p><br />", $key, $test->answer );
}
Sign up to request clarification or add additional context in comments.

2 Comments

This echos out the last number on all the answers. ex: 6 one 6 two 6 three. This is wrong it should echo out 4 one 5 two 6 three. What is causing this to happen
it shouldn't. I also simplified the code as there's no point of doing foreach() more than once. Check it now
1
foreach( $result->request->other as $key => $test )
      $tests[] = $test->answer;
            foreach($tests as $test1){
            echo "<p>$test1</p><br>";
          }

Simply change the foreach line to include a $key => before the $test variable. This will be the index (numeric or associative), and you can get that value and do as you like with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.