我在PHP中有一个名为$ definition的对象.
当我
print_r($definition);
Run Code Online (Sandbox Code Playgroud)
我明白了
数组([0] =>定义对象([extendedText] => [text] =>鼬科的几种食肉穴居哺乳动物中的任何一种,如欧亚大陆的梅勒斯蛤蜊或北美洲的红豆杉,有短腿,长爪在前脚上,还有一件厚重的灰白外套.[source] => [sourceDictionary] => ahd-legacy [citations] => Array()[labels] => Array()[score] => 0 [exampleUses] = > Array()[attributionUrl] => [seqString] => [attributionText] =>来自美国遗产®英语词典,第4版[relatedWords] =>数组()[序列] => 0 [字] = > badger [textProns] => Array()[notes] => Array()[partOfSpeech] =>名词))
如何打印"text"和"partOfSpeech"组件?
我试过$ definition-> text,$ definition [0] ['text'],$ definition ['text'] ....
我迷路了...
尝试:
echo $definition[0]->text;
和
echo $definition[0]->partOfSpeech;
它创建了对象作为数组的第一个索引:)
编辑:使用PHP,您实际上可以在数组中存储多个对象.这很酷,因为为了论证而不是传递大量的文章到视图,你可以做一些很棒的事情:
<?php
$articles = array();
for($i = 0; $i < 10; $i ++)
{
$articles[$i] = new Article("Article $i", "Hello, this is $i");
}
?>
Run Code Online (Sandbox Code Playgroud)
因此,在此示例(以及您的示例中)中,我们已将数组的索引设置为对象,而不是将变量文章设置为对象.
因此,如果我们想要提取第3篇文章,我们会这样做:
<?php
echo $articles[2]; // remember arrays start at 0 ;)
?>
Run Code Online (Sandbox Code Playgroud)
因此,使用vardump,我们可以看到它与该对象的索引关联为0.
讨厌为什么这样做.
你可以这样做但是放弃它:
<?php
$definition = array_pop( $definition[0] );
echo $definition->text;
?>
Run Code Online (Sandbox Code Playgroud)