1

I try to code a output from a API.

So I took this at first:

$api_response = json_decode(file_get_contents("--LINK TO API--"));

if I var_dump the $api_response, a code like

object(stdClass)#1 (3) {
  ["status"]=>
  string(2) "ok"
  ["count"]=>
  int(1)
  ["data"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (4) {
      ["clan_id"]=>
      int(1000001876)
      ["nickname"]=>
      string(10) "JakenVeina"
      ["id"]=>
      int(1001147659)
      ["account_id"]=>
      int(1001147659)
    }
  }
}

So if I want to output for example only the account_id, I tried more ways:

$account_id = $api_response["data"]["account_id];
echo $account_id;

and

echo $api_response->account_id;

Nothing worked for me. Does anyone have an idea?

  • Don't know if it's a typo here or in your code but you are missing one " at the end of `$account_id = $api_response["data"]["account_id];` – Andreas May 04 '16 at 08:06

3 Answers3

1

youre not asking json_decode to decode to an array.

you need (note the true):

$api_response = json_decode(file_get_contents("--LINK TO API--"), true);

then you should be able to access the array keys as needed.

Also account_id is one child level lower than you're specifying.

DevDonkey
  • 4,835
  • 2
  • 27
  • 41
  • Thanks. It work, but I have one Question left. It only works if i put [0] in the account_id variable. What is this using for? See: $account_id = $api_response['data'][0]['account_id']; //EDIT Got it, thanks :) –  May 04 '16 at 08:08
  • because `['data']` is an array of arrays – DevDonkey May 04 '16 at 08:09
0

The first level of your result is a stdclass therefore you have to use -> to get the data array. data then is an array and you access its members using [].

To get your account_id you can use:

$account_id = $api_response->data['account_id'];
-1

You have an object array so you need to access it like an object, for a numeric value, you need to use {} otherwise you can't access it.

$api_response->data->{0}->account_id; //1001147659

Also you can did the same thing using the true in the json_decode as a second parameter. If you did this in there your array would be converted as associative array and you can access it like:

$api_response['data'][0]['account_id']; //1001147659

Both will produces same result.

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42