2

so, i'm recently testing out some apis and i've come to an unexpected array that ive seen.

So, what i'm trying to do is fetch data back from the api, but the api is something i haven't seen before.

The api returns LIST: { their generated id { and the data i need to get here

Looks something like this

Here's the image

So that list { 15, the 15 can be for ex, 20 or 50 based of their ID, so i need to get the data after their generated ID.

So, is there any way i could possibly get the $decode['list'][the id number here]['id']; or other data?

Please let me know.

Flc Gen
  • 21
  • 2
  • That Data is just DUMMY from their api, it's nothing real. The problem is, they give data like this. "list": { "15": { "id": "15", "bla bla": "bla", and they said that the 15 after list { is random, based of their order id, so 15 could be 16 – Flc Gen May 01 '22 at 04:02
  • 1
    If I understand your question correctly, it is json array. Try json_decode() and then loop thru it. For reference see [this SO post](https://stackoverflow.com/questions/4731242/php-loop-through-json-array) – Ken Lee May 01 '22 at 04:13
  • Unforunately, i don't think that works. As, for each can be run, but it won't really know there's the random number or id on it. So, it should be something like this for ex, $array['list'][0]['ip'] to get the ip, but still no luck, the [0] can be 15, 16, 17, so there's not static data. – Flc Gen May 01 '22 at 04:25

1 Answers1

0

Since the id/key is dynamic you need to loop it in order to access the data.

// example object data
$list = '{
  "list": {
    "15": {
      "id": "15",
      "ip": "0:0:0:0",
      "host": "0.0.0.0",
      "port": "1234"
    },
    "16": {
      "id": "16",
      "ip": "0:0:0:0",
      "host": "0.0.0.0",
      "port": "1234"
    }
  }
}';

$decoded = json_decode($list, true);

foreach ($decoded['list'] as $key => $value) {
  echo $key . "-" . $value['id'] . " : " . $value['ip'] . "\n";
}
VLDCNDN
  • 692
  • 1
  • 7
  • 19