1

I'm trying to integrate a 3rd party service with a Restful APi (first time doing something like this). I have managed to send the query, get a response from them, and converted it into a JSON array using:

$company_json = file_get_contents($3rdparty_url);
$company_array = json_decode($company_json, true);

The problem I'm having is getting the values out of this complex array. This is what the array looks like:

{
  "response":{
    "pagination":{
      "next_url":"http:\/\/someurl.org\/companies?limit=25&offset=25",
      "total":33
    },
    "data":[
      {
        "id":"09934451",
        "name":"Acme Incorporated"
      },
      {
        "id":"00435820",
        "name":"Acme Group Limited"
      },
      {
        "id":"06841797",
        "name":"Acme Ltd"
      }
    ]
  },
  "request_id":"570bf0ca96a63"
}

I'm able to get the 'name' values out of the array by traversing it with some PHP like this:

foreach ($company_array as $data1 => $value1) {
  foreach ($value1 as $data2 => $value2) {
    foreach ($value2 as $data3 => $value3) {
      foreach ($value3 as $data4 => $value4) {
        if ($data4 == 'name') {
            print $value4;
        }
      }
    }
  }
}

But what I really want to do is grab the values and put them into some sort of format like:

<ul>
  <li id="09934451">Acme Incorporated</li>
  <li id="00435820">Acme Group Limited</li>
  <li id="06841797">Acme Ltd</li>
</ul>

From my searching around it looked like I would be able to do it with something like this, but it doesn't work. The $value4['id'] & $value4['name'], only print out the first letter of the values as if I were using $value4[0]:

foreach ($company_array as $data1 => $value1) {
  foreach ($value1 as $data2 => $value2) {
    foreach ($value2 as $data3 => $value3) {
      foreach ($value3 as $data4 => $value4) {
        print '<li id="' .  $value4['id'] . '">' . $value4['name'] . '</li>';
      }
    }
  }
}

I don't think I can be too far off but it's starting to do my head in.

1 Answer 1

1

Your over complicating it, it's very simple...

foreach ($company_array['response']['data'] as $data) {
    echo '<li id="' . $data['id'] . '">' . $data['name'] . '</li>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. That works perfectly. I had tried several things very close to what you posted, but didn't get it quite right traversing the array!

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.