PHP - Loop through Array

I have an array named, $records and when I print it the output is:

stdClass Object
(
    [questions] => Array
        (
            [0] => stdClass Object
                (
                    [question] => stdClass Object
                        (
                            [questId] => 1
                            [category] => General
                            [question] => What is your current or most recent salary?
                            [relationshipUrls] => stdClass Object
                                (
                                    [answers] => https://chp.tbe.taleo.net/chp04/ats/api/v1/object/question/1/answer
                                )

                        )

                )

            [1] => stdClass Object
                (
                    [question] => stdClass Object
                        (
                            [questId] => 2
                            [category] => General
                            [question] => What is your current or most recent title?
                            [relationshipUrls] => stdClass Object
                                (
                                    [answers] => https://chp.tbe.taleo.net/chp04/ats/api/v1/object/question/2/answer
                                )

                        )

                )
         )
)

I need to get the [answers] so that I can make another REST api GET call, but I seem to have a hard time iterating through this.

Upvotes: 0

Views: 50

Answers (2)

kimlianlopez
kimlianlopez

Reputation: 116

In a clear JSON format, your data should look like this:

$records = {
  "questions": [
    {
      "question": {
        "questId": 1,
        "category": "General",
        "question": "What is your current or most recent salary?",
        "relationshipUrls": {
          "answers": "https://chp.tbe.taleo.net/chp04/ats/api/v1/object/question/1/answer"
        }
      }
    },
    {
      "question": {
        "questId": 2,
        "category": "General",
        "question": "What is your current or most recent title?",
        "relationshipUrls": {
          "answers": "https://chp.tbe.taleo.net/chp04/ats/api/v1/object/question/2/answer"
        }
      }
    }
  ]
}

So you should be able to use a foreach loop by targeting the questions array inside of $records:

foreach($record->questions as $item) {
    $answer = $item->question->relationshipUrls->answers;

    // Do Something
    // $API_GET($answer);
}

Upvotes: 1

Javier Larroulet
Javier Larroulet

Reputation: 3237

$records is an object, not an array according to your dump.

To access the answers:

 foreach($records->questions as $rq)
 {
   print $rq->question->relationshipUrls->answers;
 }

Upvotes: 3

Related Questions