1

Im new to php. I have following situation:

$params   = array("code" => $_GET["code"], "redirect_uri" => $redirectUrl);
$response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params);

$accessTokenResult = $response["result"];

$client->setAccessToken($accessTokenResult["access_token"]);
$client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);

$response = $client->fetch("https://oauth.reddit.com/api/v1/me.json");

And the result (print_r) from $response is this one:

Array (
    [result] => Array
        (
            [name] => histograf
            [created] => 12869553489
            [gold_creddits] => 0
            [created_utc] => 12869553489
            [link_karma] => 1
            [comment_karma] => 11
            [over_18] => 1
            [is_gold] => 
            [is_mod] => 0
            [has_verified_email] => 
            [id] => ap11l
        )

    [code] => 200
    [content_type] => application/json; charset=UTF-8 )

The point is now, how can I access the element name? I need to have the username to step further in the pgm.

I've tried these and none work:

  • $username = $response[0];
  • $username = $response->name;
  • $username = $response[0]name;

2 Answers 2

1

Solution:

$username = $response['result']['name'];
  • $respone = your array.
  • ['result'] = The first element in your case.
  • ['name'] = Access the name value.
Sign up to request clarification or add additional context in comments.

Comments

0

In your example, to get the [name] field from the response:

$username = $response['result']['name'];

Replace the ['name'] with whatever field it is you are trying to access. For future reference, if you are testing the output of your script in an HTML file, you can surround your print_r() with <pre> tags as such:

<pre><?php print_r($response); ?></pre>

This makes the print_r() much more readable, and you'll be able to see the depth of the array.

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.