May 21, 2013

PHP referencing nested array values

Jpmyob’s Question:

I’m having trouble returning a value out of a nested array…

the array dump looks like this

object(myObj)#1 (3) { 
["thing1"]=> string(5) "abcde" 
["thing2"]=> string(2) "ab"
["data"]=> array(3) { 
    [0]=> string(3) "370" 
    ["id"]=> string(3) "370" 
    [1]=> string(26) "" 
    ["name"]=> string(26) "abcdefghijklmnopqrstuvwxyz" 
    [2]=> string(0) "" 
    ["address"]=> string(0) "" 
    [3]=> string(4) "wxyz" 
    ["email"]=> string(4) "wxyz"
}

I want to get to “name” inside the “data” array….

I’ve tried

echo $myObj['data']['name'];

also

echo $myObj -> $data -> $name;

they always come back as UNDEFINED.

Use

$myObj -> data['name'];

It sure is confusing. Let me explain.

The var_dump result you saw has two parts on them, one is object dump and another array .

object(myObj)#1 (3) {  <-- Starting point of object

["thing1"]=> string(5) "abcde"  <-- This is a property which has string value

["thing2"]=> string(2) "ab"     <-- This is a property which has string value


"data" here is a property of 
       object so you have to use
       $myObj -> data to access it

["data"]=> array(3) {           <-- But this is an array so you have to use 
                                    data[] to access its value
    [0]=> string(3) "370" 
    ["id"]=> string(3) "370" 
    [1]=> string(26) "" 
    ["name"]=> string(26) "abcdefghijklmnopqrstuvwxyz" 
    [2]=> string(0) "" 
    ["address"]=> string(0) "" 
    [3]=> string(4) "wxyz" 
    ["email"]=> string(4) "wxyz"
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!