如何正确显示print_r输出的数组元素?调用时遇非对象错误求解
问题:如何正确访问PHP数组中的单个元素?
使用print_r($context->correspondance)输出的数组结构如下:
Array ( [0] => Array ( [vdepart] => Biarritz [vcorrespondance] => [vid] => 864 [vtarif] => 45 [vnbplace] => 1 [vheuredepart] => 12 [vcontraintes] => soyez GENTILS ) [1] => Array ( [vdepart] => Biarritz [vcorrespondance] => [vid] => 817 [vtarif] => 4 [vnbplace] => 3 [vheuredepart] => 4 [vcontraintes] => no,n ) [2] => Array ( [vdepart] => Biarritz [vcorrespondance] => [vid] => 762 [vtarif] => 31 [vnbplace] => 3 [vheuredepart] => 6 [vcontraintes] => chien autorise ) [3] => Array ( [vdepart] => Biarritz [vcorrespondance] => [vid] => 846 [vtarif] => 862 [vnbplace] => 1 [vheuredepart] => 3 [vcontraintes] => tt ) [4] => Array ( [vdepart] => Biarritz [vcorrespondance] => [vid] => 863 [vtarif] => 1 [vnbplace] => 1 [vheuredepart] => 1 [vcontraintes] => Moi, Nicolas Guégan, vous invite tous à mon anniversaire le 18/12/2022 au trampoline park d'Avignon pour s'amusert tous ensemble ! N'héitez pas à me contacter via mon adresse mail : nicolas.guegan@alumni.univ-avignon.fr Je vous aime tous ! ) [5] => Array ( [vdepart] => Biarritz [vcorrespondance] => [vid] => 866 [vtarif] => 2 [vnbplace] => 3 [vheuredepart] => 10 [vcontraintes] => Salut ) )
尝试用echo($context->correspondance->vdepart)或echo($context->correspondance[0]->vdepart[0])访问单个字段时,报错:
Trying to get property of non-object in file...
解决方案
从输出可以明确,$context->correspondance是索引数组,内部的每个子元素也是关联数组,并非对象,因此不能用对象的->语法访问,必须使用数组下标[]:
- 访问第一个元素的
vdepart字段:
echo $context->correspondance[0]['vdepart']; // 输出结果:Biarritz
- 遍历所有元素的
vdepart字段:
foreach ($context->correspondance as $item) { echo $item['vdepart'] . '<br>'; }
报错核心原因是混淆了数组与对象的访问规则:
- 数组(无论索引/关联类型)使用
$数组变量[键名]语法访问 - 对象使用
$对象变量->属性名语法访问
此处的数组层级全程都是数组结构,所以统一用数组下标语法即可正常访问。
内容的提问来源于stack exchange,提问作者tagata tata
相关产品推荐
相关产品推荐

