Jump to content

Accessing Array Variable


StevenOliver

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.

Link to comment
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
Link to comment
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.

Link to comment
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") :-)

 

Link to comment
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.


 

 

Link to comment
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 :-)

Link to comment
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.

Link to comment
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.