如何访问数组/对象 php Notice: Undefined property: stdClass drupal 7 8

问题

我有以下数组,当我做 print_r(array_values($ get_user)); ,我得到:

Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email@saya.com [3] => Alan [4] => male [5] => Malmsteen [6] => https://www.facebook.com app_scoped_user_id/1049213468352864/ [7] => stdClass Object ( [id] => 102173722491792 [name] => Jakarta, Indonesia ) [8] => id_ID [9] => El-nino [10] => Alan El-nino Malmsteen [11] => 7 [12] => 2015-05-28T04:09:50+0000 [13] => 1 )

我试图访问数组如下:

echo $get_user[0];

但这显示我:

undefined 0

注意:

我从 Facebook SDK 4 获取此数组,因此我不知道原始数组strucutre.

如何访问数组中的 email@saya.com 值?

 

解决方法

要访问数组对象,您将如何使用两个不同的运算符.

Arrays

要访问数组元素,你必须使用 [] 或者你看不到这么多,但你也可以使用 {}  p>

echo $array[0]; echo $array{0}; //Both are equivalent and interchangeable

Difference between declaring an array and accessing an array element

定义数组和访问数组元素是两个不同的事情.所以不要混淆.

要定义数组,您可以使用 array()或者PHP> = 5.4  [] ,然后指定/设置数组/当你正在访问一个数组元素与 [] {} 如上所述,你得到的数组元素的值与设置元素相反.

//Declaring an array $arrayA = array ( /*Some stuff in here*/ ); $arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4 //Accessing an array element echo $array[0]; echo $array{0};

Access array element

要访问数组中的特定元素,您可以使用 [] {} 中的任何表达式,然后计算您要访问的键:

$array[(Any expression)]

所以只要知道你使用什么表达式作为键,以及它如何被PHP解释:

echo $array[0]; //The key is an integer; It accesses the 0's element echo $array["0"]; //The key is a string; It accesses the 0's element echo $array["string"]; //The key is a string; It accesses the element with the key 'string' echo $array[CONSTANT]; //The key is a constant and it gets replaced with the corresponding value echo $array[cOnStAnT]; //The key is also a constant and not a string echo $array[$anyVariable] //The key is a variable and it gets replaced with the value which is in '$anyVariable' echo $array[functionXY()]; //The key will be the return value of the function

Access multidimensional array

如果你有多个数组在彼此,你只需要一个多维数组.要访问子数组中的数组元素,只需要使用多个 [] .

echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"] // ├─────────────┘ ├──────────────┘ ├────────────────────────────┘ // │ │ └── 3rd Array dimension; // │ └──────────────────── 2d Array dimension; // └───────────────────────────────────── 1st Array dimension;

Objects

要访问对象属性,必须使用 - > .

echo $object->property;

如果你在另一个对象中有一个对象,你只需要使用多个 - > 来获取你的对象属性.

echo $objectA->objectB->property;

Note:

  1. Also you have to be careful if you have a property name which is invalid! So to see all problems, which you can face with an invalid property name see this question/answer. And especially this one if you have numbers at the start of the property name.

  2. You can only access properties with public visibility from outside of the class. Otherwise (private or protected) you need a method or reflection, which you can use to get the value of the property.

Arrays & Objects

现在如果你有数组和对象混合在一起,你只需要看看,如果你现在访问数组元素或对象属性,并使用相应的操作符.

//Object echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property; //├────┘ ├───────────┘ ├───────────┘ ├──────────────────────┘ ├──────┘ //│ │ │ │ └── property ; //│ │ │ └───────────────────────────── array element (object) ; Use -> To access the property 'property' //│ │ └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject' //│ └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray' //└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject' //Array echo $array["arrayElement"]["anotherElement"]->object->property["element"]; //├───┘ ├────────────┘ ├──────────────┘ ├────┘ ├──────┘ ├───────┘ //│ │ │ │ │ └── array element ; //│ │ │ │ └─────────── property (array) ; Use [] To access the array element 'element' //│ │ │ └─────────────────── property (object) ; Use -> To access the property 'property' //│ │ └────────────────────────────────────── array element (object) ; Use -> To access the property 'object' //│ └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement' //└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'

我希望这给你一个大概的想法,如果你可以访问数组和对象,当它们彼此嵌套.

Note:

  1. If it is called an array or object depends on the outermost part of your variable. So [new StdClass] is an array even if it has (nested) objects inside of it and $object->property = array(); is an object even if it has (nested) arrays inside.

    And if you are not sure if you have an object or array, just use gettype().

 

  1. Don't get yourself confused if someone uses another coding style than you:

    //Both methods/styles work and access the same data echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property; echo $object-> anotherObject ->propertyArray ["elementOneWithAnObject"]-> property; //Both methods/styles work and access the same data echo $array["arrayElement"]["anotherElement"]->object->property["element"]; echo $array["arrayElement"] ["anotherElement"]-> object ->property["element"];

Arrays, Objects and Loops

如果您不只是想访问单个元素,可以循环访问嵌套数组/对象,然后浏览特定维度的值.

为此,您只需访问要循环的维度,然后可以循环该维度的所有值.

例如,我们使用数组,但它也可以是一个对象:

Array ( [data] => Array ( [0] => stdClass Object ( [propertyXY] => 1 ) [1] => stdClass Object ( [propertyXY] => 2 ) [2] => stdClass Object ( [propertyXY] => 3 ) ) )

如果循环浏览第一个维度,您将获得第一个维度的所有值:

foreach($array as $key => $value)

这意味着在第一维只有1个元素的键( $ key ) data 和值( $ value  ):

Array ( //Key: array [0] => stdClass Object ( [propertyXY] => 1 ) [1] => stdClass Object ( [propertyXY] => 2 ) [2] => stdClass Object ( [propertyXY] => 3 ) )

如果循环浏览第二个维度,您将获得第二个维度的所有值:

foreach($array["data"] as $key => $value)

在这里,在第二维中你将有3个元素的键( $ key ) 0 , 1  和值( $ value ):

stdClass Object ( //Key: 0 [propertyXY] => 1 ) stdClass Object ( //Key: 1 [propertyXY] => 2 ) stdClass Object ( //Key: 2 [propertyXY] => 3 )

有了这个,你可以循环遍历任何你想要的维度,无论它是一个数组或对象.

Analyse var_dump() / print_r() / var_export() output

所有这三个调试功能输出相同的数据,只是以另一种格式或与一些元数据(例如类型,大小).所以这里我想展示如何读取这些函数的输出,以了解如何从数组/对象访问某些数据.

输入数组:

$array = [ "key" => (object) [ "property" => [1,2,3] ] ];

var_dump()输出:

array(1) { ["key"]=> object(stdClass)#1 (1) { ["property"]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } } }

print_r()输出:

Array ( [key] => stdClass Object ( [property] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) )

var_export()输出:

array ( 'key' => stdClass::__set_state(array( 'property' => array ( 0 => 1, 1 => 2, 2 => 3, ), )), )

所以,你可以看到所有的输出是非常相似的.如果你现在想要访问值2,你可以从值本身开始,你想访问,并工作出口到"左上".

1.我们首先看到,值2是在具有键1

的数组中

array(3) { //var_dump() [0]=> int(1) [1]=> int(2) [2]=> int(3) }

 

Array //print_r() ( [0] => 1 [1] => 2 [2] => 3 )

 

array ( //var_export() 0 => 1, 1 => 2, 2 => 3, ),

这意味着我们必须使用 []  /  {} 来访问值为2的  [1]  >,因为该值具有键/索引1.

2.接下来我们看到,该数组被分配给具有对象的name属性的属性

object(stdClass)#1 (1) { //var_dump() ["property"]=> /* Array here */ }

 

stdClass Object //print_r() ( [property] => /* Array here */ )

 

stdClass::__set_state(array( //var_export() 'property' => /* Array here */ )),

这意味着我们必须使用 - > 来访问对象的属性.  - >属性 .

到现在为止,我们知道,我们必须使用  - > property [1]  .

3.最后我们看到,最外层是一个数组

array(1) { //var_dump() ["key"]=> /* Object & Array here */ }

 

Array //print_r() ( [key] => /* Object & Array here */ )

 

array ( //var_export() 'key' => /* Object & Array here */ )

因为我们知道我们必须使用 [] 访问数组元素,我们看到这里我们必须使用  ["key"]  strong>访问对象.我们现在可以把所有这些部分放在一起,并写:

echo $array["key"]->property[1];

输出将是:

2

Don't let PHP troll you!

有几件事情,你必须知道,以便你不花时间找到它们.

  1. "Hidden" characters

    Sometimes you have characters in your keys, which you don't see on the first look in the browser. And then you're asking yourself, why you can't access the element. These characters can be: tabs (\t), new lines (\n), spaces or html tags (e.g. </p><b>), etc.

    As an example if you look at the output of print_r() and you see:

    Array ( [key] => HERE )

    Then you are trying to access the element with:

    echo $arr["key"];

    But you are getting the notice:

    Notice: Undefined index: key

    This is a good indication that there must be some hidden characters, since you can't access the element, even if the keys seems pretty correct.

    The trick here is to use var_dump() + look into your source code! (Alternative: highlight_string(print_r($variable, TRUE));)

    And all of the sudden you will maybe see stuff like this:

    array(1) { ["</b> key"]=> string(4) "HERE" }

    Now you will see, that your key has a html tag in it + a new line character, which you didn't saw in the first place, since print_r() and the browser didn't showed that.

    So now if you try to do:

    echo $arr["</b>\nkey"];

    You will get your desired output:

    HERE

  2. Never trust the output of print_r() or var_dump() if you look at XML

    You might have an XML file or string loaded into an object, e.g.

    <?xml version="1.0" encoding="UTF-8" ?> <rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>

    Now if you use var_dump() or print_r() you will see:

    SimpleXMLElement Object ( [item] => SimpleXMLElement Object ( [title] => test ) )

    So as you can see you don't see the attributes of title. So as I said never trust the output of var_dump() or print_r() when you have an XML object. Always use asXML() to see the full XML file/string.

    So just use one of the methods shown below:

    echo $xml->asXML(); //And look into the source code highlight_string($xml->asXML()); header ("Content-Type:text/xml"); echo $xml->asXML();

    And then you will get the output:

    <?xml version="1.0" encoding="UTF-8"?> <rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>