要访问
array或
object您如何使用两个不同的运算符。
数组
要访问数组元素,您必须使用,
[]或者您不会看到太多,但也可以使用is
{}。echo $array[0];echo $array{0};//Both are equivalent and interchangeable声明数组和访问数组元素之间的区别
定义数组和访问数组元素是两件事。因此,请勿将它们混淆。
要定义数组,可以使用
array()或对于
PHP> = 5.4 []并分配/设置数组/元素。当您使用[]或{}如上所述访问数组元素时,将获得与设置元素相反的数组元素的值。
//Declaring an array$arrayA = array ( );$arrayB = [ ]; //only for PHP >=5.4//Accessing an array elementecho $array[0];echo $array{0};访问数组元素
要访问数组中的特定元素,可以使用内部的任何表达式,[]或者{}将其求值为要访问的键:
$array[(Any expression)]
因此,只需要知道您用作键的表达式以及PHP如何解释它即可:
echo $array[0]; //The key is an integer; It accesses the 0's elementecho $array["0"]; //The key is a string; It accesses the 0's elementecho $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 valueecho $array[cOnStAnT]; //The key is also a constant and not a stringecho $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
访问多维数组
如果彼此之间有多个数组,则只需一个多维数组。要访问子数组中的数组元素,只需使用multiple即可[]。
echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"] // ├─────────────┘ ├──────────────┘ ├────────────────────────────┘ // │ │ └── 3rd Array dimension; // │ └──────────────────── 2d Array dimension; // └───────────────────────────────────── 1st Array dimension;
对象
要访问对象属性,必须使用->。
echo $object->property;
如果在另一个对象中有一个对象,则只需使用多个->即可获得对象属性。
echo $objectA->objectB->property;
注意:
另外,如果您使用的属性名称无效,也必须小心!因此,要查看所有问题,您可能会遇到一个无效的属性名称,请参阅此问题/答案。如果您在属性名称的开头有数字,则尤其要注意这一点。
您只能从班级外部访问具有公共可见性的属性。否则(私有或受保护的),您需要一个方法或反射,可以用来获取属性的值。
数组与对象
现在,如果您将数组和对象相互混合,则只需查看是否现在访问数组元素或对象属性并为其使用相应的运算符即可。
//Objectecho $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'//Arrayecho $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'
我希望这给您一个大概的想法,当它们相互嵌套时如何访问数组和对象。
注意:
- 是否调用数组或对象取决于变量的最外部。所以
[new StdClass]
是一个阵列,即使它已(嵌套)对象内的,并$object->property = array()
;是一个对象,即使它已(嵌套)阵列内。
并且,如果不确定是否有对象或数组,请使用gettype()。
- 如果有人使用您以外的其他编码样式,请不要感到困惑:
//Both methods/styles work and access the same dataecho $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;echo $object-> anotherObject ->propertyArray ["elementOneWithAnObject"]-> property;//Both methods/styles work and access the same dataecho $array["arrayElement"]["anotherElement"]->object->property["element"];echo $array["arrayElement"] ["anotherElement"]-> object ->property["element"];
数组,对象和循环
如果您不只是要访问单个元素,则可以遍历嵌套的数组/对象并遍历特定维的值。
为此,您只需要访问要循环的维度,然后就可以循环浏览该维度的所有值。
作为示例,我们采用一个数组,但它也可以是一个对象:
Array ( [data] => Array ( [0] => stdClass Object ( [propertyXY] => 1 ) [1] => stdClass Object ( [propertyXY] => 2 ) [2] => stdClass Object ( [propertyXY] => 3 ) ))
如果在第一个维度上循环,则将从第一个维度获取所有值:
foreach($ array as $ key => $ value)
这意味着在第一维中,您只有一个带有
key($key)data和
value($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,
2和值(
$value):
stdClass Object ( //Key: 0 [propertyXY] => 1)stdClass Object ( //Key: 1 [propertyXY] => 2)stdClass Object ( //Key: 2 [propertyXY] => 3)
这样一来,您可以遍历任何维,无论它是数组还是对象。
分析var_dump()/ print_r()/ var_export()输出
所有这3个调试功能都输出相同的数据,只是以另一种格式或带有一些元数据(例如,类型,大小)。因此,在这里我想展示如何读取这些函数的输出,以了解/了解如何从数组/对象访问某些数据。
输入数组:
$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.接下来,我们看到将数组分配给具有对象名称属性的属性
object(stdClass)#1 (1) { //var_dump() ["property"]=> }stdClass Object //print_r()( [property] => )
stdClass::__set_state(array( //var_export() 'property' => )),
这意味着我们必须使用->访问对象的属性,例如->property。
所以直到现在我们知道,我们必须使用
->property[1]。
3.最后,我们看到最外面的是一个数组
array(1) { //var_dump() ["key"]=> }Array //print_r()( [key] => )
array ( //var_export() 'key' => )
如我们所知,我们必须使用来访问数组元素[],我们在这里看到我们必须使用[“key”]来访问对象。现在,我们可以将所有这些部分放在一起并编写:
echo $array["key"]->property[1];
输出将是:
2
不要让PHP欺骗您!
您需要了解一些事情,这样您就不必花费大量时间来寻找它们。
“隐藏”字符
有时,您的按键中包含字符,这些字符在浏览器的第一次外观中不会出现。然后您问自己,为什么无法访问该元素。这些字符可以是:标签
(t),新线
(n),空格或HTML标签(例如
</p>,
<b>)等。
作为示例,如果您查看的输出,
print_r()则会看到:
Array ( [key] => HERE )
然后,您尝试通过以下方式访问元素:
echo $arr["key"];
但是您会收到通知:
注意:未定义索引:键
这很好地表明必须有一些隐藏的字符,因为即使键看起来很正确,也无法访问该元素。
这里的窍门是使用
var_dump()+查看您的源代码!(备选:
highlight_string(print_r($variable, TRUE));)
突然之间,您可能会看到以下内容:
array(1) { ["</b>key"]=> string(4) "HERE"}现在您将看到,您的密钥中带有html标记+一个换行符,这是您最初没有看到的,因为
print_r()浏览器也没有显示。
所以现在,如果您尝试执行以下操作:
echo $arr["</b>nkey"];
您将获得所需的输出:
HERE
永远不要相信XML 的输出,
print_r()或者
var_dump()如果您看XML
您可能将XML文件或字符串加载到对象中,例如
<?xml version="1.0" encoding="UTF-8" ?> <rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>
现在,如果您使用
var_dump()或,
print_r()您将看到:
SimpleXMLElement Object( [item] => SimpleXMLElement Object ( [title] => test ))
如您所见,您看不到标题的属性。因此,正如我说永远不要相信的输出
var_dump()或
print_r()当你有一个XML对象。始终用于
asXML()查看完整的XML文件/字符串。
因此,只需使用下面显示的方法之一:
echo $xml->asXML(); //And look into the source prehighlight_string($xml->asXML());header ("Content-Type:text/xml");echo $xml->asXML();然后您将获得输出:
<?xml version="1.0" encoding="UTF-8"?><rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>



