1

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.

2
  • please explain why - yes it works, but I don't understand why. Commented May 21, 2013 at 1:25
  • simple, because it's a property but also an array, then you must call $instance->property_array['key'] Commented May 21, 2013 at 1:28

1 Answer 1

5

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"
}
Sign up to request clarification or add additional context in comments.

4 Comments

You don't like make comments yah
@Sam, It is answer to the problem and not a comment. And I was 12 seconds faster than you too :P :) ha ha
please explain why - yes it works, but I don't understand why.
@jpmyob, I have added explanation too. Read it. I have explained it further.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.