0
array(85) {
  [0]=>
  object(stdClass)#9 (18) {
    ["offer_id"]=>
    string(8) "12345678"
    ["offer_name"]=>
    string(39) "Offer Name"
    ["offer_desc"]=>
    string(209) "Offer Description"
    ["call_to_action"]=>
    string(57) "Offer CTA"
    ["offer_url"]=>
    string(80) "Offer URL"
    ["offer_url_easy"]=>
    string(106) "Offer URL Easy"
  }
  [1]=>
  object(stdClass)#11 (17) {
    ["offer_id"]=>
    string(8) "87654321"
    ["offer_name"]=>
    string(24) "Offer Name 2"
    ["offer_desc"]=>
    string(107) "Offer Description 2"
    ["call_to_action"]=>
    string(107) "Offer CTA 2"
    ["offer_url"]=>
    string(80) "Offer URL 2"
    ["offer_url_easy"]=>
    string(106) "Offer URL Easy 2"
  }

I am pulling a response from an API which contains an array with objects inside. I am trying to go through each object and get the value of each key.

For example I want to output: Offer ID: 12345678, Offer ID 2: 87654321

Currently my code is only outputting one ID (the first objects ID).

$arr = $offer_data->response->offers; //Outputs above array

foreach ($arr as $value) 
{
    return $value->offer_id;
}

Output: 12345678

Note: This is inside a function that I just echo.

Been trying different ways for hours, finally coming here. Thanks for any help you provide.

1
  • Are you sure the JSON data is being interpreted as an associative array? If not it may just be a case of accessing the data like so; $value["offer_id"] Commented Dec 21, 2018 at 7:33

3 Answers 3

3

That's because you are returning at first iteration.

function test()
{
  $arr = $offer_data->response->offers; //Outputs above array

  $result = [];
  foreach ($arr as $value) {
     $result[] = $value->offer_id;
  }

  return $result;
}

$ids = test();

print_r($ids);
Sign up to request clarification or add additional context in comments.

1 Comment

That's it! As I posted the question I found that doing the foreach outside of the function it would return as expected but inside, not. That's the answer I am looking for.
1

As of PHP 7(when it started to support objects as input) you can use array_column to extract all the values in one go...

return array_column($offer_data->response->offers, "offer_id");

Comments

0

Please try this.

$arr[] = $offer_data->response->offers;

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.