PHP引用嵌套数组值

时间:2013-05-21 01:16:18

标签: php arrays

我无法从嵌套数组中返回值...

数组转储看起来像这样

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"
}

我想在“数据”数组中找到“名字”....

我试过

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

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

他们总是以未定的方式回来。

1 个答案:

答案 0 :(得分:5)

使用

$myObj -> data['name'];

这肯定令人困惑。让我解释一下。

您看到的var_dump结果有两个部分,一个是对象转储,另一个是数组。

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"
}