Jump to content
StevenOliver

Accessing Array Variable

Recommended Posts

I use a CURL script API with the header "$headers[] = 'Content-Type: application/json';"

The script ends with "$result = curl_exec($ch);"

If I simply echo the $result to  my browser, I get an array that looks like this:

stdClass Object
(
    [fromAddress] => stdClass Object
        (
            [name] => Fred Sender
            [phone] => 203-111-0000
        )

    [toAddress] => stdClass Object
        (
            [name] => Susan Recipient
            [phone] => 919-555-1212
            
What is the absolute minimum I need to do to access the phone number in the "toAddress" (919-555-1212).

Do I really need to "json_decode" this array?

I've spent 2 1/2 days trying every which way, with every permutation to access that one value:

echo $result["fromAddress"]["phone"];
echo $result->fromAddress->phone;
echo $result[0]->fromAddress->phone
echo $arr[0]->fromAddress->phone; // $arr = json_decode($result);
echo $arr->fromAddress->phone;
echo $arr[0]->fromAddress->phone;
echo $arr[0]->fromAddress["phone"];

Unfortunately I must have fallen asleep during the array lesson in PHP class  💤

Thank you.

Share this post


Link to post
Share on other sites

I thought I'd try one last thing, and of course, it works:
$result = json_decode($result,true);
echo $result["fromAddress"]["phone"];

But even though this works, I am still wondering why I cannot access the "phone" variable using Object Style:
echo $result->fromAddress->phone;

Edited by StevenOliver

Share this post


Link to post
Share on other sites
32 minutes ago, StevenOliver said:

If I simply echo the $result to  my browser, I get an array that looks like this:

stdClass Object
(
    [fromAddress] => stdClass Object
        (
            [name] => Fred Sender
            [phone] => 203-111-0000
        )

    [toAddress] => stdClass Object
        (
            [name] => Susan Recipient
            [phone] => 919-555-1212
           

As I think you figured out in your second post, it is not an array but a stdClass object.

The method to access arrays and objects is different and cannot be interchanged.

Quote

The script ends with "$result = curl_exec($ch);"

$results will be a string, and not an array nor an object.  You must use $myObj=json_encode($result) to access as an object or $myArr=json_encode($result, true) to access as an array.

Share this post


Link to post
Share on other sites

As you posted

echo $result["fromAddress"]["phone"]; 

works if $result is an array. If it's an object you need

echo $result->fromAddress->phone;

 

Share this post


Link to post
Share on other sites

What is confusing me is it is currently working with

1 hour ago, NotionCommotion said:

..You must use $myObj=json_encode($result) to access as an object or $myArr=json_encode($result, true) to access as an array.

What is confusing me is that this is working with "json_decode":

$result = json_decode($result,true);
echo $result["fromAddress"]["phone"];

But changing it to "json_encode" causes it to fail: the $result["fromAddress"]["phone"] part will not work.

(I wish I could just say "yeah it's working I'll leave it alone"..... but I always have to know "why") :-)

 

Share this post


Link to post
Share on other sites

See http://php.net/manual/en/function.json-decode.php

Quote

 

json_decode
...
json_decode — Decodes a JSON string

Description
json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed
Takes a JSON encoded string and converts it into a PHP variable.

Parameters
json
The json string being decoded.
...
assoc
When TRUE, returned objects will be converted into associative arrays.


 

 

Share this post


Link to post
Share on other sites

NotionCommotion, thank you -- I appreciate it. I think I got confused in your post where you said $myArr=json_encode($result, true), but in my code it works the oppositie : $myArr=json_decode($result, true). You have "...encode" and I have "...decode."

At first I thought you had a typo, but I've learned that some APIs respond with $result already encoded.

For years I did everything I could to avoid learning how to use Arrays... but I'm finding nowadays almost everything I encounter uses arrays, and almost all the APIs use some sort of json encoded this or that.....  I feel like I grew up never learning how to drive :-)

Share this post


Link to post
Share on other sites

Json has become ubiquitous in the web development world for a few reasons.  

  • When developers started to make heavy use of javascript in order to provide an interactive experience in their web pages, and as Ajax became a prevalent way of supporting interactivity, Json became the preferred way of getting data into javascript heavy apps.  Since json is easily converted into javascript objects, this is a lot better than having a server return html or csv or text which then has to be parsed and loaded into javascript objects.  Json helped cut out the intermediary steps and required code to either convert javascript objects and data into some other standard before sending it, and provided the same benefit when data was sent in response.
  • As REST Api's became the preferred way of accessing services, more and more of these services defaulted to JSON rather than using the verbose alternative of XML. JSON consumes less network data than JSON, and is certainly simpler to use than xml.

Obviously for PHP,  json is not a native data type, so you have json_decode() to transform json either into PHP object(s) or PHP arrays() depending on the optional 2nd parameter.  It defaults to objects, but often PHP arrays are far simpler to work with given PHP's multitude of array manipulation functions.

Conversely, when you need to return json data, json_encode() takes your PHP arrays or objects and turns them into json.    Hope this give you some historic context and clarifies a few things.

Share this post


Link to post
Share on other sites
9 hours ago, StevenOliver said:

NotionCommotion, thank you -- I appreciate it. I think I got confused in your post where you said $myArr=json_encode($result, true), but in my code it works the oppositie : $myArr=json_decode($result, true). You have "...encode" and I have "...decode."

At first I thought you had a typo, but I've learned that some APIs respond with $result already encoded.

For years I did everything I could to avoid learning how to use Arrays... but I'm finding nowadays almost everything I encounter uses arrays, and almost all the APIs use some sort of json encoded this or that.....  I feel like I grew up never learning how to drive 🙂

Steven,  My mistake and not yours.  If you have a PHP array or object, you use json_encode() to encode it into a JSON string.  Conversely, you use json_decode() to convert a JSON string into either a std object or an array (by passing TRUE as the second argument).

Don't be afraid of arrays!!!  They are too important.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.